To fetch a field value on basis of user input [duplicate] - 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'];
}

Related

Why is my PHP Mysqli code expecting a mysqli_result parameter [duplicate]

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)

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in ******/cartOutputExtra.php on line 70 Unable to retrieve order details [duplicate]

This question already has answers here:
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in
(3 answers)
Closed 6 years ago.
There have been lots of posts about this and crawled them all but can't figure out why im getting this message. I am not good with SQl and this coding so really hope someone can help.
A customer can checkout and order fine but after Sagepay always presented with the above error message. (line 70 in bold below)
$query="SELECT surname, town, county, country, currencyID, goodsTotal, shippingTotal, taxTotal, discountTotal FROM $tableOrdersHeaders WHERE orderID = '$myOrderID' AND randID = '$myRandID' LIMIT 1";
**$result = mysqli_query($query) or die( "Unable to retrieve order details");**
$num_results = mysqli_num_rows($result);
if ($num_results > 0){
// build the array from the results
$ga_order = mysqli_fetch_array($result, MYSQL_ASSOC);
} else {
die( "No matching order found");
Now the DB access file for SQLI code I believe it uses is
function connect($sql_host_name,$sql_username,$sql_password,$sql_database_name) {
$this->currentDatabase = $sql_database_name;
$this->resID = #mysqli_connect($sql_host_name,$sql_username,$sql_password);
if ($this->resID == FALSE) {
$this->lastError = "Could not connect to mySQL server";
return FALSE;
} else {
if (#mysqli_select_db($this->resID, $sql_database_name)) {
return TRUE;
} else {
return #mysqli_query($this->resID,"create database $sql_database_name");
return FALSE;
Really hope someone can help.
If you are using the procedural style of mysqli functions, you mysqli_query needs the connection variable as the first argument, followed by the query string.
It looks like you are just giving it the query string on here: $result = mysqli_query($query) or die( "Unable to retrieve order details");.
You'll want something like: $result = mysqli_query($connection, $query).
Reference: http://php.net/manual/en/mysqli.query.php

Call to a member function [duplicate]

This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 3 years ago.
I'm trying to execute a few queries to get a page of information about some images. I've written a function
function get_recent_highs($view_deleted_images=false)
{
$lower = $this->database->conn->real_escape_string($this->page_size * ($this->page_number - 1));
$query = "SELECT image_id, date_uploaded FROM `images` ORDER BY ((SELECT SUM( image_id=`images`.image_id ) FROM `image_votes` AS score) / (SELECT DATEDIFF( NOW( ) , date_uploaded ) AS diff)) DESC LIMIT " . $this->page_size . " OFFSET $lower"; //move to database class
$result = $this->database->query($query);
$page = array();
while($row = $result->fetch_assoc())
{
try
{
array_push($page, new Image($row['image_id'], $view_deleted_images));
}
catch(ImageNotFoundException $e)
{
throw $e;
}
}
return $page;
}
that selects a page of these images based on their popularity. I've written a Database class that handles interactions with the database and an Image class that holds information about an image. When I attempt to run this I get an error.
Fatal error: Call to a member function fetch_assoc() on a non-object
$result is a mysqli resultset, so I'm baffled as to why this isn't working.
That's because there was an error in your query. MySQli->query() will return false on error. Change it to something like::
$result = $this->database->query($query);
if (!$result) {
throw new Exception("Database Error [{$this->database->errno}] {$this->database->error}");
}
That should throw an exception if there's an error...
Most likely your query failed, and the query call returned a boolean FALSE (or an error object of some sort), which you then try to use as if was a resultset object, causing the error. Try something like var_dump($result) to see what you really got.
Check for errors after EVERY database query call. Even if the query itself is syntactically valid, there's far too many reasons for it to fail anyways - checking for errors every time will save you a lot of grief at some point.
I happen to miss spaces in my query and this error comes.
Ex: $sql= "SELECT * FROM";
$sql .= "table1";
Though the example might look simple, when coding complex queries, the probability for this error is high. I was missing space before word "table1".
Please check if you have already close the database connection or not.
In my case i was getting the error because the connection was close in upper line.

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

Call to a member function fetch_assoc() [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
(2 answers)
Closed 3 years ago.
I'm trying to execute a few queries to get a page of information about some images. I've written a function
function get_recent_highs($view_deleted_images=false)
{
$lower = $this->database->conn->real_escape_string($this->page_size * ($this->page_number - 1));
$query = "SELECT image_id, date_uploaded FROM `images` ORDER BY ((SELECT SUM( image_id=`images`.image_id ) FROM `image_votes` AS score) / (SELECT DATEDIFF( NOW( ) , date_uploaded ) AS diff)) DESC LIMIT " . $this->page_size . " OFFSET $lower"; //move to database class
$result = $this->database->query($query);
$page = array();
while($row = $result->fetch_assoc())
{
try
{
array_push($page, new Image($row['image_id'], $view_deleted_images));
}
catch(ImageNotFoundException $e)
{
throw $e;
}
}
return $page;
}
that selects a page of these images based on their popularity. I've written a Database class that handles interactions with the database and an Image class that holds information about an image. When I attempt to run this I get an error.
Fatal error: Call to a member function fetch_assoc() on a non-object
$result is a mysqli resultset, so I'm baffled as to why this isn't working.
That's because there was an error in your query. MySQli->query() will return false on error. Change it to something like::
$result = $this->database->query($query);
if (!$result) {
throw new Exception("Database Error [{$this->database->errno}] {$this->database->error}");
}
That should throw an exception if there's an error...
Most likely your query failed, and the query call returned a boolean FALSE (or an error object of some sort), which you then try to use as if was a resultset object, causing the error. Try something like var_dump($result) to see what you really got.
Check for errors after EVERY database query call. Even if the query itself is syntactically valid, there's far too many reasons for it to fail anyways - checking for errors every time will save you a lot of grief at some point.
I happen to miss spaces in my query and this error comes.
Ex: $sql= "SELECT * FROM";
$sql .= "table1";
Though the example might look simple, when coding complex queries, the probability for this error is high. I was missing space before word "table1".
Please check if you have already close the database connection or not.
In my case i was getting the error because the connection was close in upper line.

Categories