Why is this a bad MYSQL query in PHP? - php

Is this a bad mysql query i used in php?
$tablenamep = $_POST["tablenamep"];
$res = mysqli_query($con, "SELECT * FROM `$tablenamep` WHERE number=9");
So when i try to fetch the result using:
while ($row = mysqli_fetch_assoc($res))
There is an sql injection error :
mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given
I have read several questions and answers regarding this error, but my question is why is the query returning a boolean, when i have even added a value to $tablenamep variable. I added the value to the variable from my android app using this code :
nameValuePairs.add(new BasicNameValuePair("tablenamep", msg));
The codes are working and there aren't any errors, but my android app is crashing when i try to get the result of the php. How can i solve this! (NOTE : there is nothing wrong in my android app, i've thoroughly checked it)
Why is this a bad query? What can i do for the Query to not return a boolean, and return the actual value?

I guess your $res = mysqli_query($con, "SELECT * FROM $tablenamep WHERE number=9");
returns fails.
As what stated here in TECHNICAL DETAILS TABLE
For successful SELECT, SHOW, DESCRIBE, or EXPLAIN queries it will
return a mysqli_result object. For other successful queries it will
return TRUE. FALSE on failure
mysqli_fetch_assoc() function needs mysqli_result but the query fails that why it returns boolean instead of object.

You will find that your query has 'failed'
Insert the bit of code below
if($result === FALSE) {
die(mysql_error());
}
just above this line
while ($row = mysqli_fetch_assoc($res))
and you will find it dies at the script there.
Odds are that your posted value has a problem with it - echo out your posted value and see if it contains any ' or " etc. etc.

Related

Query returns boolean instead of mysqli_query

Need help with
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given
I'm trying to do a steamOpenID login button, but I get an error when it comes to my mysqli_query, it returns a boolean. Is it a problem with my database or in the code?
$url = "http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?
key=$_STEAMAPI&steamids=$matches[1]";
$json_object= file_get_contents($url);
$json_decoded = json_decode($json_object);
foreach ($json_decoded->response->players as $player)
{
$sql_fetch_id = "SELECT * FROM `SteamOpenID` WHERE `steamid`=$player->steamid";
$query_id = mysqli_query($db, $sql_fetch_id);
// This line triggers the warning
if(mysqli_num_rows($query_id) == 0){
$sql_steam = "INSERT INTO SteamOpenID (name, steamid, avatar) VALUES ('$player->personaname','$player->steamid','$player->avatar')";
mysqli_query($db,$sql_steam);
Firstly, mysql_query is a very old function and has been deprecated as it clearly says in the documentation.
Secondly, you don't bother to check if file_get_contents actually worked. This returns FALSE on failure. You should check the result using the strict equality comparison operator === (3 equal signs) like so:
$json_object= file_get_contents($url);
if ($json_object === FALSE) {
die("could not fetch the remote url");
}
Thirdly, you don't bother to check of the json_decode worked either. The docs say it will return NULL if the JSON cannot be decoded.
if (is_null($json_decoded)) {
die("JSON decoded as NULL");
}
You should also probably do some sanity checking on $json_decoded. But, assuming you get the array you want and assuming each player has a steamid property, it might just work.
I'd probably change your SQL definition to this:
$sql_fetch_id = "SELECT * FROM `SteamOpenID` WHERE `steamid`=" . mysql_real_escape_string($player->steamid);
You should always validate and/or escape input before you put it in your queries or you risk SQL injection.
And finally, we come to the problem at hand, which is that you don't bother to check the result of mysql_query before you just start using other functions on it. As the documentation says:
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error. You should check what it returns before to make sure it didn't return false before you start running other functions on it.
$query_id = mysql_query($sql_fetch_id);
if (!$query_id) {
die('Invalid query: ' . mysql_error());
}
You'll probably find that your SQL has an error.
EDIT: I also just noticed that you are supplying two parameters to mysql_query. The first param you supply to that function should be your SQL query string. The code you provided also doesn't tell us where you defined $db. You should probably reverse those two parameters. Read the docs and you'll see that the first parameter is the query string and the second parameter is the link identifier that you got when you called mysql_connect. It's an optional parameter. If you don't supply it, the function will use the last connection opened using mysql_connect.

Error accessing MySQL database with PHP object (nested queries)

I want to get some data from a Sphinx server and pass it to MySQL to execute some queries. I'm new to PHP so probably I'm missing something here. I've looked for similar questions but can't find anything so maybe you can help me.
The error is in the first while. I'm pretty sure it's due to the $rown variable but don't know the reason. (I've verified that I can retrieve data from the connections so it is passing the data where the error lies - could be the sql syntax of the query but that seems fine).
Edited the code thanks to the comments below, now I get the error: Warning: mysqli_fetch_object() expects parameter 1 to be mysqli_result, boolean given in C:\Apache24\htdocs\test3.php on line 20. This is because the query failed, I still suspect it is because $rown.
$sphinxcon = mysqli_connect...
$mysqlcon = mysqli_connect...
$query = "SELECT names FROM iproducts LIMIT 0,1000";
$raw_results= mysqli_query($sphinxcon, $query);
//Until here works ok, now I want to pass $raw_results to MySQL
while ($row = mysqli_fetch_object($raw_results)) {
$rown = $row->names;
$mquery = "SELECT text FROM claims WHERE EXISTS ($rown) LIMIT 0,1000";
$mysqlresults = mysqli_query($mysqlcon, $mquery);
while ($final = mysqli_fetch_object($mysqlresults)) //this is line 20
{
printf ("%s<br />", $final->text);
}
}
Thanks :)
Well $row contains an object, so would have to use it as such, maybe
$rown = (string)$row->names;
... assuming you want the variable to contain the 'names' attribute you just SELECTed from Sphinx index.
As for the mysql EXISTS(), no idea what you really doing here, seems confused. How you structured it currently suggests that 'names' attribute in sphinx contains a complete SELECT query, that mysql could execute for the exists condition. That seems unlikely.
Guessing you meaning to more normal query something like
$mquery = "SELECT text FROM claims WHERE text LIKE '%$rown%' LIMIT 0,1000";
But that is subject to SQL injection, particully if names might contain single quotes. SO should escape it. Perhaps
$rown = mysqli_real_escape_string($mysqlcon, $row->names);
But might be worth reading up on prepared queries.
btw, the 'Error' you getting, is because you creating an invalid query and not dealing with it. So $mysqlresults is FALSE.
$mysqlresults = mysqli_query($mysqlcon, $mquery) or die("Mysql Error: ".mysqli_error($link)."\n");

SQL Sanitization Output/Datatype Error

I'm attempting to sanitize the input of some PHP/SQL code, but I keep receiving the following error when checking the number of rows:
mysqli_num_rows() expects parameter 1 to be mysqli_result
It feels like I'm missing a method to convert/handle the query after execution, and there is little in the documentation to bridge this gap. Assuming $conn is a properly connected mysqli database call, here is my code:
$qry = mysqli_prepare($conn,'SELECT * FROM table WHERE attribute=?');
mysqli_stmt_bind_param($qry,'s',$_SESSION['string']);
mysqli_stmt_execute($qry);
/* Should something go here? */
if(mysqli_num_rows($qry) > 0)
{
//foo
}
I avoided object notation because it wasn't working either - this simply appeared a little more explicit, but I'm not opposed to either method.
Looking forward to hearing any thoughts - thank you in advance!
I don't use mysqli very often, but I believe the issue stems from the fact you are trying to call the mysqli_num_rows() method against a sql string. After running the execute command, pull the results of the execution into a variable and pass that into your mysqli_num_rows() call.
// Added this to capture the results of the execution
$result = mysqli_stmt_get_result($qry);
if(mysqli_num_rows($result) > 0)
{
//foo
}
Okay, so I was able to discover a way to count the number of rows and retrieve the db output:
$stmt = mysqli_prepare($conn, 'SELECT blah FROM table WHERE attribute=?');
mysqli_stmt_bind_param($stmt,'s',$string);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
mysqli_stmt_bind_result($stmt,$bindingvar);
mysqli_stmt_fetch($stmt);
if(mysqli_stmt_num_rows($stmt) > 0) {
//foo
}
And output is now assigned to $bindingvar.
It's cumbersome, but it does everything I want it to, and it's nice and procedural.
It should be noted this method doesn't work well for more than one result from a database, but given the level of problems with "get_result()" this is far better than nothing.
Hope this helps!
- M

mysql_fetch_assoc(): supplied argument is not a valid MySQL [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 9 years ago.
I have created an android application,by using this function in php i am creating a
a new user in database mysql.
function signUp($sName, $sMobile, $sAddress, $sEmail, $sPwd)
{
$sql = "insert into customers (name,mobile,address,email,pwd) values ('$sName','$sMobile','$sAddress','$sEmail','$sPwd')";
$run = $this->query($sql);
if ($this->result <= 0) {
return false;
} else {
return $this->json('DATA');
}
}
With the below function i am querying in database and returning the response in json format
function query($sql){
$query = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_assoc($query)){
$this->result[] = $row;
}
return $this;
}
but the response i am getting has an error i tried surpessing the warnings by using
#mysql_fetch_assoc($query)
It gave a proper response in browser but android gets null as response
Error:
Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL
result resource in
Warning: Cannot modify header information - headers already sent by
(output started at
Help required New to PHP. Thanks in advance
INSERT QUERY does not return RESULT SET
Only SELECT query returns result set
You can't get result by Insert Query but you can get id of current inserted user by mysql_insert_id() and then you can use "Select Query" against that id.
Well, the thing is that Your query is INSERT query and, according, to PHP Manual, in successful query it return true, not mysql object. So function "mysql_fetch_assoc($query)" cannot be ran because it requests mysql object as parameter not only TRUE.
Also, I recommend to start using MySQLi or PDO extensions, instead of mysql_* functions.
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning
resultset, mysql_query() returns a resource on success, or FALSE on
error.
For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc,
mysql_query() returns TRUE on success or FALSE on error.
The returned result resource should be passed to mysql_fetch_array(),
and other functions for dealing with result tables, to access the
returned data.
Use mysql_num_rows() to find out how many rows were returned for a
SELECT statement or mysql_affected_rows() to find out how many rows
were affected by a DELETE, INSERT, REPLACE, or UPDATE statement.
mysql_query() will also fail and return FALSE if the user does not
have permission to access the table(s) referenced by the query.

mysqli_num_rows() expects paramter though an earlier query on the same page works

I am getting an error when querying a table in my MySQL database. It's the standard one with mysqli_num_rows when there is no value in the variable that's being passed:
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in folder/file.php on line 29
Problem is I can't find the syntax error. I've looked at it a ton of times. Here's what my code is:
$sql_messages = "SELECT * FROM messages WHERE to='$userid'";
$result_messages = $mysqli->query($sql_messages);
$num_rows_messages = mysqli_num_rows($result_messages);
I tried a fetch array but that gave me the similar error. Nothing is getting passed into $result_messages I suppose. I echo'ed out $userid and that has a value and I've checked my database and there is a table 'messages' with a field 'to'. I'm connected to the right database because I have this code before this query:
$sql="SELECT * FROM users WHERE firstname='$firstname' && lastname='$lastname'";
$result = $mysqli->query($sql);
$row = mysqli_fetch_array($result);
And that works fine. It is the third query on the page, is there some sort of limit? Does anyone see a syntax error that I'm overlooking? Thanks, sorry if it's a small little error!
It's because $mysqli->query() returned boolean FALSE, which, according to the mysqli::query() docs, it does when an error happens. You can get more detail on the error by accessing $mysqli->errno and $mysqli->error.
I'm guessing that the root of the problem lies in the query which references a column called to, which is a MySQL reserved word. Try surrounding the word to in your query with backticks. Like this:
$sql_messages = "SELECT * FROM messages WHERE `to`='$userid'";
Really, though you should avoid naming columns and tables reserved words. Consider renaming the column if feasible.

Categories