Reputation:
I want to check the input of the user after he hits the submit button if the word exist in the database.
Hence, I have this code. However, it always says Data does not exist in which it finds the condition false.
What is wrong with my code below?
$input_word = trim($_POST["word"]);
$data_check = "SELECT * FROM word_collections WHERE single_word = '$input_word'";
$a = mysqli_query($data_check);
if (mysqli_num_rows($a) == 1)
{
echo "Data exist.";
}
else
{
echo "Data DOES NOT exist";
}
Upvotes: 1
Views: 1258
Reputation: 3593
Best way to do this.
$dbhost = 'localhost';
$dbuser = 'username';
$dbuser = 'password';
$dbpass = 'dbname';
$dbConn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
$query = "SELECT * FROM word_collections WHERE single_word = '$input_word'";
$result = $dbConn->query($query);
if($result->num_rows == 1){
echo "have some records";
}else{
echo "No records";
}
Upvotes: 0
Reputation: 121
$input_word = trim($_POST["word"]);
$data_check = "SELECT * FROM word_collections WHERE single_word = '$input_word'";
$con = mysqli_connect("host",'id','pass','dbname'); // add this connection
$a = mysqli_query($con,$data_check);
if (mysqli_num_rows($a) == 1)
{
echo "Data exist.";
}
else
{
echo "Data DOES NOT exist";
}
You need to put your connection in mysqli_query parameter 1. You may refer tutorial from w3schools .
Upvotes: 0
Reputation: 74217
Your query failed because you didn't pass db connection to:
$a = mysqli_query($data_check);
The variable for the connection is unknown, so you need to base yourself on:
$a = mysqli_query($connection, $data_check);
and you may have to use >0
instead of ==1
for your num_rows()
as there could be more than one record.
Your code is also open to an sql injection; use a prepared statement.
Use PHP's error reporting and mysqli_error($connection)
on the query.
Also make sure that your connection is in fact mysqli_
and not another api.
Upvotes: 5