I trying to check if a username is already in use in my db but it's not echoing anything (blank page when i run ) , i want to get a true or false response
<?php
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("data1") or die(mysql_error());
$usercheck = "john";
$sanitizeduser= filter_var($usercheck, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
$check = mysql_query("SELECT EXISTS(SELECT 1 FROM users WHERE username = $sanitizeduser)");
echo $check;
?>
You have shuffled with mysqli_query
and mysql_
functions
Try this,
$link = mysqli_connect("localhost","root","","data1") or die("Error " . mysqli_error($link));
$usercheck = "john";
$sanitizeduser= filter_var($usercheck, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
$result = $link->query("SELECT username FROM users WHERE username = '".$sanitizeduser."' ");
$row_cnt = $result->num_rows;
if($row_cnt>0){
echo "User Exists"; // echo 1;
}else{
echo "No User found"; //echo 0;
}
You are mixing mysql and mysqli:
So your problem is just a typo, just change the function name:
<?php
$link = mysqli_connect("localhost", "root", "password","data1");
if (!$link){
// error handling goes here: mysqli_error()
}
$usercheck = "john";
$sanitizeduser= filter_var($usercheck, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
$check = mysqli_query($link,"SELECT EXISTS(SELECT 1 FROM users WHERE username = $sanitizeduser) as check");
?>
Also to display the result you can't just use echo $check
, you will have to use something like mysqli_fecth_array
for example. See the manual
Example:
while($row = mysqli_fecth_array($check)) {
echo $row["check"] . "<br>";
}