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
Related
This question already has answers here:
MySQLI Prepared Statement: num_rows & fetch_assoc
(5 answers)
Closed 5 years ago.
I am trying to search a table for specific items using a prepared statement in PHP. I am getting no errors, but also getting no record. Here is my code:
$items = [];
$search = "john";
if ($stmt = $this->con->prepare("SELECT * FROM phptest WHERE search = ?")) { //'john'";
$stmt->bind_param("s",$search);
$stmt->execute();
while ($row = mysqli_fetch_array($stmt)) {
$item = [];
$item['id'] = $row['id'];
$item['first'] = $row['search'];
$item['last'] = $row['data'];
array_push($items, $item);
}
}
return $items;
Now, when I don't use a prepared statement, and just SELECT * FROM phptest I get all the results in the table (including the item where search = 'john'). Furthermore, if I use the query SELECT * FROM phptest WHERE search = 'john' I get the one record where search = 'john'
But as soon as I turn it into the prepared statement, I get zero errors but zero records. I do get a warning:
mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given
Which made me think my bind_param or execute() was returning FALSE, but when I check, it does not appear to be returning false.
I started off my adventure working through the tutorial https://www.simplifiedcoding.net/android-mysql-tutorial-to-perform-basic-crud-operation/, which I thought I understood fully but ran into my error when trying to make my own PHP API.
I then went to the manual http://php.net/manual/fr/mysqli.prepare.php, but still cannot find my error.
Though it has been closed as "off-topic," I have reviewed PHP bind_param not working and found nothing applicable to my situation.
Likewise, I am not finding the error in PHP bind_param not defined nor php bind_param is not working.
You're very close. mysqli_fetch_array() expects to be passed a result object, not the statement object itself:
$stmt = $conn->prepare(...);
$stmt->bind_param(...);
$stmt->execute();
$result = $stmt->get_result();
while ($row = mysqli_fetch_array($result)) {
Or, in the fully OO manner:
while ($row = $result->fetch_array()) {
This question already has answers here:
mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource
(31 answers)
Closed 6 years ago.
I have a line of code in my php that reads:
$sel_venue = "SELECT 'char_type' FROM 'character_type_allowed' WHERE status='Open'";
$run_venue = mysqli_query($con,$sel_venue);
while ($row = mysqli_fetch_array($run_venue))
if ($row['char_type'] == 'Mortal')
{ print ("<li><a href='http://houston-by-night.com/sheets/create/mortal.php'>Create Mortal</a></li>"); }
The link associated with this does nothing. Zero interaction beyond acting likeit wants to expand. My error log produces this: Why is it asking for this?
[08-Aug-2016 23:28:41 America/New_York] PHP Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in /home/houchat/public_html/incl/creation.php on line 8
You can't use ' as ticks for field/tablenames.
Your query is producing an error. You can see the error with mysqli_error($con).
Please see the corrected code below
$sel_venue = "SELECT `char_type` FROM `character_type_allowed` WHERE status='Open'";
$run_venue = mysqli_query($con,$sel_venue) or die(mysqli_error($con));
while ($row = mysqli_fetch_array($run_venue)) {
if ($row['char_type'] === 'Mortal') {
print ("<li><a href='http://houston-by-night.com/sheets/create/mortal.php'>Create Mortal</a></li>");
}
}
Your query failed, so $run_venue is the boolean false instead of what you expect. You should check for errors before you use any query result. Do this:
$run_venue = mysqli_query(...);
if(!$run_venue) die(mysqli_error($con));
... //<- we get here if the query succeeded
You will see the error. The problem is that your SQL statement wraps the table name between single quotes 'character_type_allowed', instead of backticks (backtick is above the tab key on my keyboard)
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.
As a part of a login system I need to check if the username exists in the database so I created a query that checks if the username the user entered already exists.
With mysql_result I check if the id is larger as null. If yes: user exists and if not the user doesn't exist. But here it goes wrong and wampserver gives me this error:
Warning: mysql_result() expects parameter 1 to be resource, object given in users.php on line 6
function user_exists($username){
global $user_db;
$username = sanitize($username);
$query = mysqli_query($user_db , "SELECT COUNT(`id`) FROM `users` WHERE `username` = '$username'");
$result = mysql_result($query, 0); //line 6
if(!$result){
return false;
}else{
return true;
}
}
and this is the code that calls that function:
if(user_exists('name') === true){
echo 'exists';
}
$user_db = mysqli_connect("localhost","root","","databaseName");
What did I try:
if I do this: mysqli_result($result,0,"id"); I get this error: Call to undefined function mysqli_result().
got this suggestion from this question
All the answers on questions like mine say that you should not use mysql
and mysqli both but only one of them but when I only use mysli I get the error like I told one paragraph above this one.
So can somebody tell me how to fix this.
You are mixing mysql and mysqli a bit. There is no function mysqli_result() in mysqli driver. However I found a solution to your problem. From comment in PHP documentation:
Converting an old project from using the mysql extension to the mysqli
extension, I found the most annoying change to be the lack of a
corresponding mysql_result function in mysqli. While mysql_result is a
generally terrible function, it was useful for fetching a single
result field value from a result set (for example, if looking up a
user's ID).
The behavior of mysql_result is approximated here, though you may want
to name it something other than mysqli_result so as to avoid thinking
it's an actual, built-in function.
The code:
<?php function mysqli_result($res, $row, $field=0) {
$res->data_seek($row);
$datarow = $res->fetch_array();
return $datarow[$field]; }
?>
Source: http://php.net/manual/en/class.mysqli-result.php
This question already has answers here:
mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource
(31 answers)
Closed 8 years ago.
I am trying to fetch a field value(SecurityQues) on basis of user input(username).
Following is the code:
$substr=substr($usrnm,0,2);
if($substr=="AC")
{
$res="SELECT SecurityQues FROM reg_ac WHERE UserName=$usrnm";
}
else
{
$res="SELECT SecurityQues FROM reg_indi WHERE UserName=$usrnm";
}
$result = mysql_query($res,$db_handle);
$result = mysql_query($res);
while($row = mysql_fetch_assoc($result))
{
echo $row['SecurityQues'];
}
But i am getting the following warning:
Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\my on line 120
That error message is caused by the fact that your query has an error and fails to execute and you have no error checking in place to catch that.
Since username is a string, it needs to be inside quotation marks or else your query will keep on failing like it currently does.
$res="SELECT SecurityQues FROM reg_ac WHERE UserName='$usrnm'";
^ ^
And don't execute your query two times. Although that is not causing your current error but that is just waste of resources and unnecessary .
Even after that fix, your query is so prone to injections it could bring down your mysql server before you can blink your eye.
How can I prevent SQL injection in PHP?
Remove this one
$result = mysql_query($res);
And change this one
if($substr=="AC")
{
$res="SELECT SecurityQues FROM reg_ac WHERE UserName=$usrnm";
}
else
{
$res="SELECT SecurityQues FROM reg_indi WHERE UserName=$usrnm";
}
To this one
if ( $substr == "AC") $res = "SELECT SecurityQues FROM reg_ac WHERE UserName = '{$usrnm}'";
else $res = "SELECT SecurityQues FROM reg_indi WHERE UserName = '{$usrnm}'";
Ignoring the fact that you are prone to SQL injection and that the original Mysql API is deprecated there is an error in your query as pointed out by Hanky Panky. At the line :
$result = mysql_query($res,$db_handle);
The result of the variable $result is initialized to the boolean false which is not a valid argument for mysql_fetch_assoc.
You can get more information on what is happening with something like this :
$result = mysql_query($res,$db_handle) or die ("Error in query: $query. ".mysql_error());
You should really consider using Mysqli and prepared statement to avoid SQL injection and something like this comic strip from happening.
this is not the best way to achieve this, but
If i stick to your code, he is the correction (removing second mysql_query, prone to your error) :
$substr=substr($usrnm,0,2);
if($substr=="AC")
{
$res="SELECT SecurityQues FROM reg_ac WHERE UserName='$usrnm'";
}
else
{
$res="SELECT SecurityQues FROM reg_indi WHERE UserName='$usrnm'";
}
$result = mysql_query($res,$db_handle);
while($row = mysql_fetch_assoc($result))
{
echo $row['SecurityQues'];
}