SQL query doesn't seem to work - php

I'm trying to run the following query but it doesn't seem to work properly and an error comes back with:
Warning: mysqli_fetch_row() expects parameter 1 to be mysqli_result, boolean given in C:\wamp\www\VACANCY\pages\search\booking2.php on line 83
Which is while:
$row = mysqli_fetch_row($Result)
All I want to is to return the chosen JOB_TITLE AND LOCATION from my jobs table. Please any help would be great as I have spent hours trying to solve it.
<?php
$Query = "(SELECT FROM jobs " .
"WHERE jobs.JOB_TITLE ='$_POST[JOB_TITLE]' " .
"AND jobs.LOCATION = '$_POST[LOCATION]')";
$Result = mysqli_query($DB, $Query);
while ($row = mysqli_fetch_row($Result))
{
echo $row['JOB_TITLE'] . " " . $row['LOCATION'];
echo "<br />";
}
?>

You need to add something after SELECT. For example, SELECT JOB_TITLE, LOCATION FROM...

Your statement is "SELECT FROM", so you don't indicate what you want to select. If you query "SELECT * FROM" then all fields will be selected and the query will work.
But please be aware that your code is very insecure. The POST value from the search form can be manipulated by an attacker and the query can be used e.g. to truncate the whole table. Read more at http://www.tizag.com/mysqlTutorial/mysql-php-sql-injection.php.

Related

mysqli gives 0 result for query in php but gives correct result in terminal

I've got two tables and an association table of those two. I'm trying to run a query which gives my desired result running the code from terminal, but gives zero or unknown column result if executed from php.
This is my query:
$result = $mysqli->query("SELECT * FROM projects p
JOIN projects_groups pg on p.projectid = pg.projectid
JOIN groups g on g.groupid = pg.groupid
WHERE p.projectid = 'bestproject'");
Running the code exactly like above gives me back 0 result. If i switch 'bestproject' with a variable it gives me back an unkwown column bestproject error.
What's wrong with my query?
UPDATE: I had a stupid error in my function that was recieving the result, which caused my confusion. The receiver function was showing an empty array when the query was successfull, and also the function that handled the query was showing empty or failed result when the query was wrong (Not the one above). I kept searching for the error in the query instead to look at somewhere else. Sorry for wasting your time.
Everything you have done there is selected what tables and content. You need to have a php function that writes out the content as well.
Example:
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
As you can see so does the echo writing out the content of the tables. You also can make so you don't have to use $row['id'] Just save it in a another variable:
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$id = $row['id'];
$first = $row['firstname'];
$last = $row['last'];
echo "id: $id - Name: $first $last<br>";
}
} else {
echo "0 results";
}
Of course you need to have some content in the tables
The first problem does not make sense to me. The unknown column error is caused because you didn't use the single quotes so MySQL will try to find a column with your variables name instead of handling it as a value.
$result = $mysqli->query("SELECT * FROM projects p
JOIN projects_groups pg on p.projectid = pg.projectid
JOIN groups g on g.groupid = pg.groupid
WHERE p.projectid = '".$argument."'");
To avoid SQL injection it's better to use PDO to pass arguments. http://php.net/manual/en/book.pdo.php
Thank you for the answers, you helped me to look somewhere else.
The truth is that i've made a mistake somewhere else. I was loading the result into an array while i only wanted to get one result, and the function that recieved it was actually trying to get data out of a different variable...
It's kinda embarassing, but i've spent hours to figure it out, so i had to ask.
Sorry and thanks for the help!

mysql query works with plain text, but not with variable

I am trying to print out some topic information, but it is not going so well. This is my query:
SELECT * FROM topics WHERE id='$read'
This doesn't work. I've echo'ed the $read variable, it says 1. So then if I do like this:
SELECT * FROM topics WHERE id='1'
It works perfectly. I don't get what is the problem. There's no hidden characters in $read or anything else like that.
Try like this:
$query = "SELECT * FROM topics WHERE id='" . $read . "'"
ID is normally a numeric field, it should be
$id = 1;
$query = "SELECT * FROM topics1 WHERE id = {id}"
If you are using strings for some reason, fire a query like
$id = '1';
$query = "SELECT * FROM topics1 WHERE id = '{$id}'"
SELECT * FROM topics WHERE id=$read
it consider it as string if you put i single quotes
I wonder why all the participants didn't read the question that clearly says that query with quotes
SELECT * FROM topics WHERE id='1'
works all right.
As for the question itself, it's likely some typo. Probably in some other code, not directly connected to $read variable
try
$query = sprintf("SELECT * FROM topics WHERE id='%s';",$read);
Also remember to escape the variable if needed.
Looks like you might have an issue with the query generation as everyone else is pointing to as well. As Akash pointed out it's always good to build your query in to a string first and then feed that string to the MySQL API. This gives you easy access to handy debugging techniques. If you are still having problems try this.
$id = 1;
$query = "SELECT * FROM `topics1` WHERE `id`={$id}";
echo ": Attempting Query -> {$query}<br />";
$res = mysql_query($query, $dblink);
if($res <= 0)
die("The query failed!<br />" . mysql_error($dblink) . "<br />");
$cnt = mysql_num_rows($res);
if($cnt <= 0)
{
$query = "SELECT `id` FROM `topics1`";
echo "No records where found? Make sure this id exists...<br />{$query}<br /><br />";
$res = mysql_query($query, $dblink);
if($res <= 0)
die("The id listing query failed!<br />" . mysql_error($dblink) . "<br />");
while($row = mysql_fetch_assoc($res))
echo "ID: " . $row['id'] . "<br />";
}
This will at least let you monitor between calls, see what your query actually looks like, what mysql says about it and if all else fails make sure that the ID you are looking for actually exists.
try with this : SELECT * FROM topics WHERE id=$read

select data from row error

I have some code which selects data from a row. It is working and prints the result correctly, but I have an error I can not figure out.
$rs=array();
$select=array ("system_name", "location", "alarmtype", "severity", "start_time", "end_time", "duration", "reason","shift_oparation", "system_oparation");
for ($i=0;$i<=9;$i++){
$SQL = "SELECT (".$select[$i].") FROM (".$is.") WHERE duration=('".$ic."') AND location=('".$id."')";
$result = mysql_query($SQL);
$db_field = mysql_fetch_array($result);
$rs[$i]=$db_field[$select[$i]];
echo $rs[$i];
}
Echo prints correctly, but there is an error:
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given.
I think some of your queries dont return anything. In order to get rid of the warning you should check if the $result was in fact a resource.
Try this:
$rs=array();
$select=array ("system_name", "location", "alarmtype", "severity", "start_time", "end_time", "duration", "reason","shift_oparation", "system_oparation");
for ($i=0;$i<=9;$i++){
$SQL = "SELECT (".$select[$i].") FROM (".$is.") WHERE duration=('".$ic."') AND location=('".$id."')";
$result = mysql_query($SQL);
if($result){
$db_field = mysql_fetch_array($result);
$rs[$i]=$db_field[$select[$i]];
echo $rs[$i];
}
}
However, your code will be a lot more efficient if you use only one query.
You are doing something really strange. It looks like $select is a list of columns in a table, and you are fetching them one column at a time!
You can select them all at once, with this query:
$sql = "SELECT system_name, location, alarmtype, severity,
start_time, end_time, duration, reason, shift_oparation, system_oparation
FROM " . $is . " WHERE duration = '" . $ic . "' AND location = '" . $id . "'";
Note I've removed some extraneous parenthesis you had. Also be very careful with building SQL queries dynamically like this. I'm assuming you know the values of $is, $ic, and $id to be safe from SQL injection attacks,
Run the result, and then iterate over the row array
$result = mysql_query($sql);
if ($result)
{
$row = mysql_fetch_array($result); //fetches the first result row as an array
// Can be accessed like $row['system_name']
foreach ($row as $key => $value)
echo $key, " = ", $value;
}
else
die(mysql_error() . $sql);
If the result is false, it will perform the die statement and print out the error returned from MySQL and also the query we built, so you can see if it looks correct.
Warning: mysql_fetch_array() expects parameter 1 to be resource,
boolean given in.
This means that mysql query produced errors .
Return Values
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning
resultset, mysql_query() returns a resource on success, or FALSE on
error.
Use mysql_error to display teh error and see why it happened.
e.g.
if(!$result){
echo mysql_error();
}
Protip: donlt use mysql libraries as noted in php manual
there is problem in select statement please check the select query or you can run individual select query and check the output

How to check if a row exists in MySQL using PHP

I am trying to read in an XML file and compare it to fields in an existing database.
If the ID in the database doesn't exist in the XML file, then the whole row corresponding to the Id is no longer valid and will be deleted.
To do this I read in each line of the XML from start to finish in a while statement.
As step one I am trying to do a simple compare, and echo if it finds an Id in the database that doesn't exist in the XML.
I know there are some Ids in the database that don't exist in the XML, but the following code is not displaying them.
I've got three questions, firstly how would I display the Id that is pulled from the database, and secondly why isn't this code finding any ids that are not in the XML?
The final question is am I going about this completely the wrong way and is there a better way to do it!
$sql_result = mysql_query("SELECT id FROM `list` WHERE id = $id") or die(mysql_error());
if($sql_result)
{
// echo $id . " Id exists " . $sql_result["id"] . "\n";
}
else
{
echo "Id no longer exists" . $id . "\n";
}
Your code isn't finding what you expect because even though the id may not be found, $sql_result still holds a TRUE value because the query was successful. Instead, check if myqsl_num_rows() > 0
if($mysql_num_rows($sql_result) > 0)
{
// echo $id . " Id exists "\n";
//Now, to print the id, you need to fetch it from `$sql_result`,
//which is just a resource at this point:
$row = mysql_fetch_assoc($sql_result);
echo $row['id'];
}
This is the proper way to check:
$sql_result = mysql_query("SELECT `id` FROM `list` WHERE `id` = ".intval($id,10)." LIMIT 0,1");
if(is_resource($sql_result) && mysql_num_rows($sql_result) > 0 ){
$sql_result = mysql_fetch_assoc($sql_result);
echo $id . " Id exists " . $sql_result["id"] . "\n";
}
else{
echo "Id no longer exists" . $id . "\n";
}
You should check the number of rows returned using mysql_num_rows(). Otherwise, you are simply checking to see if the query executed without any error.
if($sql_result)
to
if(mysql_num_rows($sql_result))
You can use NOT IN() on your select with the IDs that exist on you XML like:
SELECT id FROM `list` WHERE id NOT IN($your_id_list)
With this you'll have a list of IDs that are not in the list.
Your IDs must be separated with a comma like:
SELECT id FROM `list` WHERE id NOT IN(123,654,987,45)
Question 1: how would I display the Id that is pulled from the database?
$sql_result = mysql_query("SELECT `id` FROM `list` WHERE `id` = $id") or die(mysql_error());
$sql_row = mysql_fetch_assoc($sql_result);
if(!empty($sql_row['id'])) {
echo "Id exists - " . $sql_row['id'] . "\n";
} else {
echo "Id no longer exists - " . $sql_row['id'] . "\n";
}
Question 2: why isn't this code finding any ids that are not in the XML?
I think in your code the if() condition will always return true irrespective if the Id exists in the database or not. And secondly as you might have guessed from my code above, you are missing to fetch the data from the SQL resultset
Question 3: am I going about this completely the wrong way and is there a better way to do it?
You are doing it the right way by browsing through the XML and checking each entry in the database for existence. A better way might be to first retrieve all IDs from the XML and then use them in the single SQL query:
SELECT `id` FROM `list` WHERE `id` NOT IN ($list);
Please note that this query might run slow if there are a very large number of IDs in the XML file, say a few hundreds.
mysql_num_rows()
Or
SELECT COUNT(*) [...]

Retrieving results for query from MySQL using PHP

I want to query a MySQL database. I have the following. $name keeps changing in a loop. ($query is a sample query here)
$query = "SELECT id FROM table1 WHERE name='$name';";
$result = mysql_query($query) or die(mysql_error());
echo "$result<br/>";
While ($row = mysql_fetch_array($result)) {
echo $row["id"] . " - " . $row["name"];
}
with the echo "$result<br/>" it just prints something like Resource id #. Nothing from $row is printed. The MySQL connection is fine. If I run the query without PHP, it works fine. What might be wrong?
Everything is correct, you'll get nothing from $result until you use some function like mysql_fetch_array() or mysql_fetch_assoc() like you do in your loop.

Categories