Two WHERE statements [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result
I've done a search and couldn't find anything that could specifically help me.
I was hoping you could help.
I'd like to execute a MySQL query which searches a table for entries which meet two criteria (type = green AND on = yes)
I am presented with: Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /link/to/my/file.php on line 36
Here is an extract from the code (line 36):
`$green = "SELECT * FROM homepage_vars WHERE type = 'green' AND on = 'yes'";
$green = mysql_query($green);
$green = mysql_fetch_array($green);`

ON is a MySQL reserved keyword. If you use it as a column or table identifier, you need to enclose it in backquotes:
SELECT * FROM homepage_vars WHERE type = 'green' AND `on` = 'yes'
You'll then have another problem once the query syntax is corrected. You have overwritten the variable $green several times. Originally, it held your query SQL, but was then used for the query result resource. That's fine, but then you will overwrite it with the row fetched by mysql_fetch_array() and its contents will be an array or FALSE. Subsequent attempts to fetch rows will fail since $green is no longer a result resource.
Always test for query success or failure before attempting to fetch rows. Call mysql_error() to see the error reported by the MySQL server, which would have pointed to invalid syntax near 'on or something similar.
$green = "SELECT * FROM homepage_vars WHERE type = 'green' AND on = 'yes'";
$query = mysql_query($green);
if ($query) {
// Don't overwrite your query resource!
// Use a new variable!
$row = mysql_fetch_array($query);
}
else {
// Failure!
echo mysql_error();
}

Related

Uncaught PDOException: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens [duplicate]

This question already has an answer here:
Can I use a PDO prepared statement to bind an identifier (a table or field name) or a syntax keyword?
(1 answer)
Closed 5 years ago.
I'm failing to see the problem why I'm getting a pdo error, I'm not missing a simple : or a parameter (since there are only 2)
public function does_stringid_excist($strTable, $strColumn, $strValue)
{
$sql = "SELECT count(1) AS count FROM tblemployer WHERE :strColumn = :strValue";
$this->objDatabase->query($sql); //Makes a prepare with the given sql
// $this->objDatabase->bind_column(':strTable', $strTable);
$this->objDatabase->bind_column(':strColumn', $strColumn); // Uses the `bindColumn()` from PDO
$this->objDatabase->bind_value(':strValue', $strValue); // Uses the `bindValue()` from PDO
$result = $this->objDatabase->single();
return $result['count'];
}
SELECT count(1) AS count FROM `tblemployer` WHERE `employerID` = :strValue" works just fine so the error isn't with the value.
A column is not the same as a table. Youre using bindColumn to bind a table, which does not work.
See: http://php.net/manual/en/pdostatement.bindcolumn.php

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)

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

Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result
I'm having a problem with this mysql code. I presume its a basic error in the $sqlx... line but I'm slightly lost.
The code basically prints messages from a db
Here is the code:
$sqls="SELECT username FROM social WHERE `adder`='$username'";
$results=mysql_query($sqls);
$resulti= mysql_num_rows($results);
if ($resulti==0) {
echo "You haven't added anyone yet. Find some suggestions";
}
$row=mysql_fetch_array($results);
$sqlx="SELECT * FROM messages WHERE `sender` IN ($row)";
$resultx= mysql_query($sqlx);
$resultz= mysql_num_rows($resultx);
if ($resultz==0){
echo "No messages at all!!";
}
else {
$finished="false";
$r=0;
While(($rowx=mysql_fetch_assoc($resultx))&&($finished=="false")) {
//echo off messages
$username is got further up the file.
Here is the error:
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home/user/public_html/social/iframe/index.php on line 34
Line 34 is $resultz= mysql_num_rows($resultx);
But like i said the error is probably the line two up from that.
One interesting happens. "No messages at all!!" is echoed out which means the result of the mysql_query is 0. This is why I am convinced it is the line 32, ($sqlx)
Any idea??
Have I done the mysql_fetch_array wrong when getting $row??
thanks
$row=mysql_fetch_array($results);
$sqlx="SELECT * FROM messages WHERE `sender` IN ($row)";
This will create the following query:
SELECT * FROM messages WHERE `sender` IN (Array)
This is obviously not a valid MySQL query. You have to process the array.
$sqlx = "SELECT * FROM `messages` WHERE `sender` IN ("; // start of query
foreach($row as $r)
$sqlx .= "'".$r['username']."',"; // insert all returned usernames
$sqlx = substr($sqlx,0,-1).')'; // substract the last comma and close the query
Or, as RiaD pointed out in the comments:
$sqlx = "SELECT * FROM `messages` WHERE `sender` IN (".
implode(',',array_map(function($x){return "'".$x['username']."'"; }, $row)).
")";
PS: Riad, it should be $x['username'] instead of $x and you forgot the semicolon ;)
mysql_query($sqlx) return false instead of result. It means any error occured. Try to check is $sqlx correct query and check mysql_error() to get what error is occured. To check was here any error or not you can use
if(!$resultx){
print 'error:'.mysql_error();
}
else{
//use result
}
If your query fails mysql_query($sqlx) returns false rather than resource. So, you need to check, that this function returned true (e.g. if (!results) {}) nad print use mysql_error() to see what error was.
if(!$resultx){
print 'error:'.mysql_error();
}
Also, you are embedding $row variable into the query string. But this var is an Array, so you end up with a query like this:
SELECT * FROM messages WHERE `sender` IN (Array)
See mysql_fetch_array manual for details

Categories