mysql_num_rows() error boolean given [duplicate] - php

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 7 years ago.
i've got this part of code in my php app
$find_user = "SELECT * FROM tcms_module_profiles WHERE profile_contact_email = ".$_POST['email'];
$num_rows = mysql_num_rows(mysql_query($find_user));
that return this error message:
mysql_num_rows() expects parameter 1 to be resource, boolean given
But i'm passing a query result to mysql_num_rows(). I've checked the query and it's correct (because if i execute it on phpMyAdmin it return the record).
Thanks in advance for all the help

You need to put your profile_contact_email values in quotes because to insert VARCARE field we need quotes around it. And use mysql_real_escape_string in your query to prevent sql injection
$email = mysql_real_escape_string($_POST['email']);
$find_user = "SELECT * FROM tcms_module_profiles WHERE
profile_contact_email = '".$email."'";
$result = mysql_query($find_user);
$num_rows = mysql_num_rows($result);
Note:- mysql is deprecated instead use mysqli or PDO

Your SQL query failed, resulting in mysql_query returning a boolean FALSE value. It failed because you didn't use quotes around your email.
Your script is also open to SQL injection, btw.

Use the following code:
$find_user = "SELECT * FROM `tcms_module_profiles` WHERE `profile_contact_email`='{$_POST['email']}';";
$result = mysql_query($find_user);
if(!$result){die("ERROR");}
$num_rows = mysql_num_rows($result);
Your code was missing '' around $_POST['email'] and you should check first for the query to be true. mysql_ is deprecated use mysqli_ or PDO extension. Mysqli & PDO
A mysqli version of above code
$find_user = "SELECT * FROM `tcms_module_profiles` WHERE `profile_contact_email`='{$_POST['email']}'";
$result = mysqli_query($find_user);
if(!$result){die("ERROR");}
$num_rows = mysqli_num_rows($result);
Note - you also need to change your mysql connection variables according to mysqli.

Try this...
$find_user = "SELECT * FROM tcms_module_profiles WHERE profile_contact_email = '".$_POST['email']."'";

Related

PHP not showing MySQL results with variable in query [duplicate]

This question already has answers here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
How can I prevent SQL injection in PHP?
(27 answers)
Reference - What does this error mean in PHP?
(38 answers)
Closed 2 years ago.
I have been using the same code for years and all of a sudden I'm having problems that I cannot figure out. I am making a very simple query to MySQL in PHP using a variable in the statement. When I use the variable, it returns no results. When I manually type in the value of the variable instead, it works. I use this syntax all day long and never have had a problem. What on earth is wrong?
$name = "Fred";
$query = "SELECT * FROM database WHERE name='".$name."'";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) != 0) {
echo "Found record.";
}
If I replace the $name variable with Fred, it finds the record. If I echo the query with the variable before it executes and place that exact statement into MySQL directly in phpMyAdmin, I also get the result. If I leave the statement as-is with the variable in place, I get no result. Please help.
your query states SELECT * FROM database WHERE name='".$name."', this means that your table name is database, now i dont know how you actually created this table but database is a MYSQL reserved keyword change the name of your table to something else or just change your query to
$query = "SELECT * FROM `database` WHERE name='$name'";
assuming that your database connection is fine your code should now work
also worth noting, whenever acquiring data from a database use prepared statements instead of raw data as it makes you vulnerable to sql injection, in your case your code should be something like this
$name = "Fred";
$stmt = $dbconnection->prepare("SELECT * FROM table_name WHERE name=?")
$stmt->bind_param("s", $name);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows != 0)
{
echo "Found record.";
}
this is more secure
You shouldn't use mysqli excepted for old projects you can't upgrade, it's outdated and suffers from potential sql injection vulnerabilities.
Instead, I recommand you to learn PDO and prepared statements.
Your request should look like this :
$name = 'Fred';
$sql = "SELECT * FROM my_user_table WHERE name = :name";
// You should have set your pdo instance in a script handling your database connexion and reusing it in any script making requests.
$result = $pdo->prepare($sql);
// Here you dynamically inject values in your request and tells pdo what type of data you are expecting
$result->bindValue(':name', $name, PDO::PARAM_STR);
$result->execute();
if( $result->rowCount()) {
echo "{$result->rowCount()} result(s) found";
}
else {
echo 'No result found';
}
Here's the official doc :
https://www.php.net/manual/fr/book.pdo.php
This will also more than probably fix your problem.

Error Query PHP after migrate to mysql database

I have execute query using PHP which previously executed on mssql server database . Now with the same table and data. I using mysql database to execute my query. But error happen. Any suggestion for my query below in order to can execute using mysql database :
$year = mysql_query("SELECT * FROM education_year ORDER BY id DESC");
if (isset($_GET['year'])){
$educationyear= mysql_fetch_array(mysql_query("SELECT * FROM educationyear WHERE year='{$_GET['year']}'"));
}else {$educationyear = mysql_fetch_array($year);}
$kode['KODE'] = mysql_fetch_array(mysql_query("SELECT KODE FROM educationyear WHERE year='$educationyear'"));
$result = mysql_query("SELECT * FROM Province");
while($row = mysql_fetch_array($result))
{
$xd = mysql_fetch_array(mysql_query("SELECT COUNT (*) AS total FROM child WHERE id_province='{$row['province_code']}' AND education='A'
AND educationyear='{$educationyear['KODE']}'"));
}
Error message like below :
Notice: Array to string conversion in C:\xampp\htdocs\xy\demo.php on line 19
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\xy\demo.php on line 20 .
Its line when execute $xd query.
There are a few problems with your code
1st: When you use an array within double-quoted string, do not quote the array key. Change
"...WHERE year='{$_GET['year']}..."
"...WHERE id_province='{$row['province_code']}'..."
To:
"...WHERE year='{$_GET[year]}..."
"...WHERE id_province='{$row[province_code]}'..."
2nd: The design pattern below is not good:
mysql_fetch_array(mysql_query("SELECT...")
You're taking the result of mysql_query and feeding it directly to mysql_fetch_array. This works as long as the query succeeds and returns a resource. If the query fails, it will return FALSE and mysql_fetch_array will trigger the error you see:
mysql_fetch_array() expects parameter 1 to be resource, boolean given
Instead, make sure there is no error before proceeding
$result = mysql_query("SELECT...")
if($result===false){
//Query failed get error from mysql_error($link).
//$link is the result of mysql_connect
}
else{
//now it's safe to fetch results
$record = mysql_fetch_array($result);
}
3rd: do not use mysql_ functions. They have been abandoned for years and have been removed from the most recent version of PHP. Switch to MySQLi or PDO
4th: learn about prepared statements. You're using user supplied input directly in your query ($_GET['year']) and this makes you vulnerable to SQL injection.

PHP $_GET['id'] and security [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 9 years ago.
I have links on my webpage like this: http://test.com/index.php?function=news&id=88
So whenever I put a ' after 88, I get the following error: Warning: mysql_fetch_row() expects parameter 1 to be resource, boolean given in ... line 588
So I read about mysql_real_escape_string(), but I'm getting the ID not posting and I have no clue how should I prevent getting this error.
function news()
{
$query = mysql_query("SELECT * FROM news WHERE id=".$_GET['id']."");
while($news = mysql_fetch_row($query))
{
...
}
}
The easy way is to cast the id to integer, if the id is an integer that is:
$id = (int)$_GET['id'];
But it's strongly recomended to use pdo or mysqli with prepared statements:
http://php.net/manual/en/book.pdo.php
http://php.net/manual/en/book.mysqli.php
You can do a redirect whenever mysql_fetch_row() don't return anything (i.e. because there is no id 89)
Something like:
if (!$row = mysql_fetch_row($result)) {
header(Your error page);
}
Warning: mysql_fetch_row() expects parameter 1 to be resource
This means the the $result = mysql_query(....); call you made before the mysql_fetch_row() failed and resulted FALSE instead of a Resource ( i.e. a handle to the query result );
Look at the query, post it if possible, that is where your problem is.
Your code assumes that the query was successful without checking. For debugging purposes, add an 'or die(mysql_error())' line to the end of the mysql_query() statement.
$query = mysql_query("SELECT * FROM news WHERE id=".$_GET['id']."") or die( mysql_query() );
For more robust error handling in production applications, check the value of $query and log an error if it is false.
if (false === $query ) {
// Log error and/or notify an administrator
}
else {
while($news = mysql_fetch_row($query)) ...
As pointed out in other answers, you should ensure that the value of the id parameter is an integer since your query assumes that it will be. You can do this by casting:
(int)$_GET['id']
or via more robust type checking
if ( !is_numeric( $_GET['id'] ) ) {
// Take appropriate action
}
else {
// Create and execute the query

mysql_query error with single quotes in php [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I handle single quotes inside a SQL query in PHP?
I had written the following code to fetch a data from a mysql table:
$clg=$row['text'];
$query1 = "SELECT * FROM user WHERE text='$clg'";
$result1 = mysql_query($query1,$con) or die(mysql_error());
$count=mysql_num_rows($result1);
echo $count;
But the text field has a single quote(') which closes the single quotes in $query1, hence resulting in mysql syntax error. How can I rectify this?
$clg=$row['text'];
$query1 = "SELECT * FROM user WHERE text='" . mysql_real_escape_string($clg) . "'";
$result1 = mysql_query($query1,$con) or die(mysql_error());
$count=mysql_num_rows($result1);
echo $count;
But you should know that mysql_* functions family will be deprecated soon.
Please read the red box here located on php.net website.
<?php
function escape($string) {
if(get_magic_quotes_gpc()) $string = stripslashes($string);
return mysql_real_escape_string($string);
}
write this function and call it
escape($clg);
for prevent every mysql syntax error and sql injection.`

"mysql_fetch_assoc()" error when data in mysql field is changed

I have a mySQL database from where I fetch some data via PHP.
This is what I've got:
if ($db_found) {
$URL_ID = $_GET["a"];
$SQL = "SELECT * FROM tb_employees WHERE URL_ID = $URL_ID";
$result = mysql_query($SQL);
while ($db_field = mysql_fetch_assoc($result)) {
$firstname = $db_field['firstname'];
$surname = $db_field['surname'];
$function = $db_field['function'];
$email = $db_field['email'];
$telnr = $db_field['telnr'];
}
mysql_close($db_handle);
}
else {
print "Database not found... please try again later.";
mysql_close($db_handle);
}
The URL_ID field in my mySQL database is, for this example, 001. When I go to www.mydomain.com/index.php?a=001 it fetches all the data, puts it into a variable, and I can echo the variables without any problem.
Now, I want to change the URL_ID, and I've changed it to "62ac1175" in the mySQL database. However, when I proceed to www.mydomain.com/index.php?a=62ac1175, I get this error message:
Warning: mysql_fetch_assoc() expects parameter 1 to be resource,
boolean given in
mydomain.com\db_connect.php on line 17
The field in mySQL has varchar(8) as type and utf8_general_ci as collation.
If I change the entry back to 001 and change my URL to ?a=001, it works fine again.
What's going wrong?
You are not doing any error checking in your query, so it's no wonder it breaks if the query fails. How to add proper error checking is outlined in the manual on mysql_query() or in this reference question.
Example:
$result = mysql_query($SQL);
if (!$result)
{ trigger_error("mySQL error: ".mysql_error());
die(); }
your query is breaking because you aren't wrapping the input in quotes. You can avoid* quotes only for integers (which 62ac1175 is not). Try
$SQL = "SELECT * FROM tb_employees WHERE URL_ID = '$URL_ID'";
Also, the code you show is vulnerable to SQL injection. Use the proper sanitation method of your library (like mysql_real_escape_string() for the classic mysql library that you are using), or switch to PDO and prepared statements.
In your code, this would look like so: Instead of
$URL_ID = $_GET["a"];
do
$URL_ID = mysql_real_escape_string($_GET["a"]);
* however, if you avoid quotes, mysql_real_escape_string() won't work and you need to check manually whether the parameter actually is an integer.

Categories