Retrieving results for query from MySQL using PHP - 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.

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!

php wont return same as sql query

ok, so I have a search script with is sort of working but I dont get the results I want.
when i run the query in php it doesnt result anything.
$searchStr = htmlspecialchars($searchStr);
$sql = "SELECT * FROM steamitems WHERE steamid='" . $id . "' AND name LIKE '%".$searchStr."%'";
$r_query = mysqli_query($link, $sql);
but if I run the exact same output as $sql (SELECT * FROM steamitems WHERE steamid='76561198196240283' AND name LIKE '%sawed%') in phpmyadmin it returns the correct result..
EDIT: I forgot to mention that I obviously print the results here
while ($row = mysqli_fetch_array($r_query)){
echo $row["assetid"];
echo $row["name];
}

INNER JOIN works with * but not with a single field

If i use the following line in PHP the MySQL query works perfectly fine:
$query = "
SELECT *
FROM customers_1
JOIN customers_2
ON customers_1.id = customers_2.cus_id;
";
but when i try to just get two single fields like this:
$query = "
SELECT customers_1.product,customers_1.id
FROM customers_1
JOIN customers_2
ON customers_1.id = customers_2.cus_id;
";
it doesnt work at all, means i do not get any output. When i copy and paste the second query and put it into PHPMyAdmin it works perfectly fine.
What i do afterwards is this:
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
if($row['id']=="3")
{
foreach($row as $field)
{
echo $field;
}
}
}
mysql_close($dbhandle);
Because $row['id'] is nothing in your code because you just fetch one column from your query SELECT customers_1.product.. and that column is product
And no need foreach loop . You just get your value in single while loop
Updated Answer after question updated
while ($row = mysql_fetch_array($result)) {
if (!empty($row['id'])) {
echo $row['id'];
}
}
Note:- Mysql is deprecated instead use mysqli or PDO
You are comparing id in your code while your query is retrieving customers_1.product.

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 print results in php using AVG and CHAR_LENGTH in MySQL Query

How do I show the results for $wordavg in php. I have done the query in SQL on database after taking out variables so I believe the query is correct but don't know how to show the results of the search in php.
$usertable = 'words';
$yourfield = 'wordname';
$query = "SELECT AVG(CHAR_LENGTH( wordname)) AS $wordavg FROM $usertable WHERE $yourfield LIKE '"."$current_letter"."%' ";
$result = mysql_query($query);
First, you should be using mysqli instead. Back to your question, usually you can iterate over a result with a loop as follows:
while ($row = mysql_fetch_assoc($result)) {
echo $row['field'];
}
More info and examples in the PHP mysql_query doc.
Since you only have one row of data to return, you don't need the loop part. You can simply use
$row = mysql_fetch_assoc($result);
$wordavg = $row['wordavg'];
You shouldn't have the $ in wordavg in your query. It should be just ...AS wordavg FROM...

Categories