How do I get columns from a joined table in PHP? - php

For a single table, I normally do something like this:
$length = 42;
$result = mysql_query ('SELECT * FROM table WHERE length = "' . $length . '"', $dbconn);
$rowsfound = mysql_num_rows ($result);
if ($rowsfound == 1) {
$row = mysql_fetch_array ($result);
$tableid = $row ['table_id'];
$tablecloth = $row ['tablecloth'];
$height = $row ['height'];
...
But how to I get the rows from a joined table like this:
$chairid = 123;
$result = mysql_query ('SELECT * FROM table,chair WHERE chair.id = "' . $chairid . '" AND table.table_id = chair.table_id', $dbconn);
$rowsfound = mysql_num_rows ($result);
if ($rowsfound == 1) {
$row = mysql_fetch_array ($result);
$tableid = $row ['table.table_id'];
$tablecloth = $row ['table.tablecloth'];
$height = $row ['table.height'];
...
This doesn't return any values in $table.tablecloth. What am I doing wrong?

do this with JOIN instead
SELECT * FROM table
INNER JOIN chair ON table.table_id = chair.table_id
WHERE chair.id = "' . $chairid . '"

The reason you are not getting any results is because your query is failing. table is a reserved word so you need to add back ticks around it as follows:
$result = mysql_query ('SELECT * FROM `table`,`chair` WHERE `chair`.id = "' . $chairid . '" AND `table`.table_id = `chair`.table_id', $dbconn);
You would had figured this out if you had proper error handling in place like following (note the or die():
$result = mysql_query ('SELECT * FROM `table`,`chair` WHERE `chair`.id = "' . $chairid . '" AND `table`.table_id = `chair`.table_id', $dbconn) or die(mysql_error())
Please refer to the list of reserved words here: http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
Apart from this, as Kim pointed out you also need to fix the extra closing parenthesis.

You would be better doing a proper JOIN like echo_Me suggested but this is the proper syntax for the way you are coding it.
$result = mysql_query ('SELECT table.*,chair.* FROM table,chair WHERE chair.id = "' . $chairid . '" AND table.table_id = chair.table_id', $dbconn);
Then
if ($rowsfound == 1) {
$row = mysql_fetch_array ($result);
$tableid = $row ['table_id'];
$tablecloth = $row ['tablecloth'];
$height = $row ['height'];
The results do not get returned with the table name in front of the column names. This can cause a problem if you have a column name with the same name in both tables.

I think you have extra closing parenthesis?? )
$tableid = $row ['table.table_id']);
$tablecloth = $row ['table.tablecloth']);
$height = $row ['table.height']);

Related

I Have this headache with PHP and MySQL

I have this problem:
function search_by_name($mysql, $name, $lastname)
{
$query = 'SELECT idKlienci FROM Klienci WHERE Imie = "' . $name . '"
AND Nazwisko = "' . $lastnem . '"';
$result = $mysql->query($query);
$row = mysqli_fetch_array($result); // I want to get the ID' of table `Klienci1`
// and here i don't know how many dimentions have this array
echo $row[0][0]; // prints nothing
}
$lastnem != $lastname
So change the query to use the correct variable name
$query = 'SELECT idKlienci
FROM Klienci
WHERE Imie = "' . $name . '"
AND Nazwisko = "' . $lastname . '"';
To make this kind of code easier to read you can also make use of the fact that variables in a double quoted string are automatically expanded. Which make this easier to read and therefore debug.
$query = "SELECT idKlienci
FROM Klienci
WHERE Imie = '$name'
AND Nazwisko = '$lastname'";
$result = $mysql->query($query);
// use mysqli_fetch_assoc() then you get only one assoc array
// so you can use named parameters to the array.
// the names will match the column names in the table
//$row = mysqli_fetch_array($result);
// also mysqli_fetch_assoc() only returns one row at a time
$row = mysqli_fetch_assoc($result);
// a row is always one dimensional so do
echo $row['id'];
So if you have more than one row in the resultset of your query you have to get the results in a loop
$result = $mysql->query($query);
while ( $row = mysqli_fetch_assoc($result)) {
echo $row['id'] . '<br>';
}
Now you should see both rows
MYSQL doesn't use double quotes for strings, it uses simple quotes:
$query = "SELECT idKlienci FROM Klienci WHERE Imie = '$name' AND Nazwisko = '$lastname'";
You can also add the variable directly into PHP strings when you're using double quotes, without the need to concatenate them.
Your Argument name $lastname & used variable $lastnem name are not same.
try this :
$row = mysqli_fetch_array($result);
echo $row[0];

Output of DISTINCT and <> from SQL Query issue

I am obtaining some values from an array and making a match against these values in an SQL Query.
The code for this is as follows:
foreach($files as $ex){
$search = substr($ex,3,4);
echo $search . '<br>';
echo '<br>';
$sql = 'SELECT DISTINCT `pdb_code` FROM pdb WHERE `pdb_code` <> "' . $search . '" LIMIT 4';
}
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo 'SQL' . $row['pdb_code'] .'<br>';
$pdb[] = $row['pdb_code'];
}
The issue that I am having is that the <> seems not to be working.. I have even tried using the != operator, but still having the same issue.
The output of $search from the array are :
101m
102l
102m
103l
The output of SQL from the query is still:
101m
102l
102m
103l
Your code doesn't seem that logical, as you generate numerous SQL statements and then just execute the last one.
However I assume what you want to do is take a list of files, extract a string from each file name and then list all the pdb_code values from the table which are not already in the string.
If so something like this would do it. It takes each file name, extracts the sub string and escapes it, putting the result into an array. Then it builds one query, imploding the array to use in a NOT IN clause:-
<?php
$search_array = array();
foreach($files as $ex)
{
$search = substr($ex,3,4);
echo $search . '<br>';
echo '<br>';
$search_array[] = mysql_real_escape_string($search);
}
if (count($search_array) > 0)
{
$sql = "SELECT DISTINCT `pdb_code` FROM pdb WHERE `pdb_code` NOT IN ('" . implode("','", $search_array) . "') LIMIT 4";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo 'SQL' . $row['pdb_code'] .'<br>';
$pdb[] = $row['pdb_code'];
}
}
You have to use not in:
SELECT * FROM table_name WHERE column_name NOT IN(value1, value2...)
Try this:
$searchIds = implode(',',$search);
$sql = "SELECT DISTINCT `pdb_code` FROM pdb WHERE `pdb_code` NOT IN ('$searchIds') LIMIT 4";

MySQL does not retrieve first item in PHP

I've now been trying for hour and can't figure the problem out. I've made a php file that fetch all items in a table and retrieves that as JSON. But for some reason after I inserted the second mysql-query, it stopped fetching the first item. My code is following:
...
case "LoadEntryList":
$result2 = performquery("SELECT * FROM Entries WHERE Category = '" . $_POST["Category"] .
"' LIMIT " . $_POST["Offset"] . ", " . $_POST["Quantity"] . "");
$row2 = $result2->fetch_assoc();
while($row = $result2->fetch_assoc()) {
$result3 = performquery("SELECT Username FROM Users WHERE ID = '" . $row2["UserID"] . "'");
$row3 = $result3->fetch_assoc();
echo substr(json_encode($row),0,
strlen(json_encode($row))-1) . ",\"Username\":\"" . $row3["Username"] . "\"}";
}
...
Any help is greatly appreciated.
EDIT: Thanks for all those super fast responses.
First you're fetching a row:
$row2 = $result2->fetch_assoc();
Then you start looping at the next row:
while($row = $result2->fetch_assoc()) {
If you want to loop over all of the rows, don't skip the first one. Just loop over all of the rows:
$result2 = // your very SQL-injectable query
while($row2 = $result2->fetch_assoc()) {
$result3 = // your other very SQL-injectable query
$row3 = $result3->fetch_assoc();
// etc.
}
Note that errors like this would be a lot more obvious if you used meaningful variable names. "row2", "result3", etc. are pretty confusing when you have overlapping levels of abstraction.
Important: Your code is wide open to SQL injection attacks. You're basically allowing users to execute any code they want on your database. Please look into using prepared statements and treating user input as values rather than as executable code. This is a good place to start reading, as is this.
No Need of $row2 = $result2->fetch_assoc();
<?
case "LoadEntryList":
$result2 = performquery("SELECT * FROM Entries WHERE Category = '" . $_POST["Category"] .
"' LIMIT " . $_POST["Offset"] . ", " . $_POST["Quantity"] . "");
while($row = $result2->fetch_assoc())
{
$result3 = performquery("SELECT Username FROM Users WHERE ID = '" . $row["UserID"] . "'");
$row3 = $result3->fetch_assoc();
echo substr(json_encode($row),0,strlen(json_encode($row))-1) . ",\"Username\":\"" . $row3["Username"] . "\"}";
}
?>
Or,
<?
...
case "LoadEntryList":
$Category=$_POST["Category"];
$Offset=$_POST["Offset"];
$Quantity=$_POST["Quantity"];
$result3 = performquery("SELECT Entries.*, Users.Username FROM Entries, Users WHERE Entries.Category=$Category AND Entries.UserID=Users.ID LIMIT $Offset, $Quantity");
$row3 = $result3->fetch_assoc();
echo substr(json_encode($row),0,strlen(json_encode($row))-1) . ",\"Username\":\"" . $row3["Username"] . "\"}";
}
...
?>
I have a addition to David answer(can't comment on it yet)
This line of code:
$result3 = performquery("SELECT Username FROM Users WHERE ID = '" . $row2["UserID"] . "'");
will always return with the same result. If you were to change $row2[... into $row[... the code would take the rows that get updated by the while loop.
I am not content with the accepted result. The snippet can be fixed / replaced, and also a bad code must be replaced. Also not to mention is that I don't know if anyone spotted a really big mistake in the output. Here is the fix and I'll explain why.
$JSON = array();
$result2 = performquery( '
SELECT
e.*, u.Username
FROM Entries AS e
LEFT JOIN Users AS u ON u.ID = e.UserID
WHERE
e.Category = ' . $_POST['Category'] . '
LIMIT ' . $_POST['Offset'] . ', ' . $_POST['Quantity'] . '
' );
while( $row2 = $result2->fetch_assoc() ){
$JSON[] = $row2;
}
echo json_encode( $JSON );
Obviously the main issue is the query, so I fixed it with a LEFT JOIN, now the second part is the output. First it's the way you include the username, and the second what if you had multiple results? Than your output will be:
{"ID":1,"Username":"John"}{"ID":2,"Username":"Doe"}
How do you parse it? So the $JSON part comes in place. You add it to an array and will encode that array. Now the result is:
{["ID":1,"Username":"John"],["ID":2,"Username":"Doe"]}
LE: I left out the sql inject part which as stated by the OP, will be done afterwards? I'm not sure why not do it at the point of writing it, because you may forget later on that you need to sanitize it.

PHP checking if query returns anything error

I've been pondering about this for a while, I'm trying to see if the query wields any results and I want to do something if it doesn't return any results.
PHP:
<?php
session_start();
$host = "localhost";
$user = "root";
$passw = "";
$con = mysql_connect($host, $user, $passw);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$json = $_REQUEST['json'];
$json = stripslashes($json);
$jsonobj = json_decode($json);
$me = $jsonobj -> me;
$other = $jsonobj -> other;
mysql_select_db("tinyspace", $con);
$result = mysql_query("SELECT * FROM friends WHERE (user_id = '" .$me. "' AND user_id2 = '" .$other. "') OR (user_id2 = '" .$me. "' AND user_id1 = '" .$other. "')");
if(mysql_num_rows($result) > 0)
{
}
the if statement keeps giving me problems however.
Any Advice?
just to be sure, how many columns do you have named userid? user_id, user_id1, user_id2 ?
do you mean user_id1 in place of user_id in the below line, by any chance?
$result = mysql_query("SELECT * FROM friends WHERE (user_id = '" .$me. "' AND user_id2 = '" .$other. "') OR (user_id2 = '" .$me. "' AND user_id1 = '" .$other. "')");
If so, maybe thats why you aren't fetching any results.
Edit:
$result = mysql_query("SELECT * FROM friends WHERE (user_id1 = '" .$me. "' AND user_id2 = '" .$other. "') OR (user_id2 = '" .$me. "' AND user_id1 = '" .$other. "')");
you should try
<?php
if($result == false){
//what you want to do if the query returns nothing
}else{
//handle the result
}
for those who think my answer is incorrect or the opposite of what is asked, please read the question from the beginning again, very carefully.
mysql_num_rows() is okay to use for checking if you have results, and should work in your example..
However, if your call to mysql_num_rows() doesn't work as expected (i.e. always false), it's almost always down to a problem with the query.
mysql_num_rows() expects a result resource, and if there is a problem with your query, mysql_query will return a false.
You can amend your mysql_query() call to
mysql_query("sql here") or die(mysql_error());
That should give you an idea if the error lies in the query. Once you've checked your query is working as expected, your mysql_num_rows() will start functioning correctly.
Additionally, the mysql_ functions are depreceated, you should take a look at Prepared Statements http://php.net/manual/en/pdo.prepared-statements.php
$result = mysql_query("SELECT * FROM `friends` WHERE (`user_id1` = '" .$me. "' AND `user_id2` = '" .$other. "') OR (`user_id2` = '" .$me. "' AND `user_id1` = '" .$other. "')");
to simply answer your question, while it seems that while your code is potentially vulnerable, it should act as you intend. This is what I use in my connection class
public function makeQuery(){
if($result = mysqli_query($this->link, $this->sql)){
if(mysqli_num_rows($result) != 0){
while($r = mysqli_fetch_array($result)){
$return[] = $r;
}
mysqli_free_result($result);
return $return;
}else{
return 0;
}
}else{
// db error here
}
}
This assumes you feed the class some value for $sql and $link... but you can then check for either an integer return or an array return. if it is an integer (0), it had no rows, an array will be the returned rows. If there is an error it will fall into the error logic (I send myself an email in this case).

PHP query does not return result

This query is not returning any result as there seems to be an issue with the sql.
$sql = "select region_description from $DB_Table where region_id='".$region_id."' and region_status =(1)";
$res = mysql_query($sql,$con) or die(mysql_error());
$result = "( ";
$row = mysql_fetch_array($res);
$result .= "\"" . $row["region_description"] . "\"";
while($row = mysql_fetch_array($res))
{
echo "<br /> In!";
$result .= " , \"" . $row["region_description"] . "\"";
}
$result .= " )";
mysql_close($con);
if ($result)
{
return $result;
}
else
{
return 0;
}
region_id is passed as 1.
I do have a record in the DB that fits the query criteria but no rows are returned when executed. I beleive the issue is in this part ,
region_id='".$region_id."'
so on using the gettype function in my php it turns out that the datatype of region_id is string not int and thus the failure of the query to function as my datatype in my tableis int. what would be the way to get parameter passed to be considered as an int in php. url below
GetRegions.php?region_id=1
Thanks
Try it like this:
$sql = "SELECT region_description FROM $DB_Table WHERE region_id = $region_id AND region_status = 1"
The region_id column seems to be an integer type, don't compare it by using single quotes.
Try dropping the ; at the end of your query.
First of all - your code is very messy. You mix variables inside string with escaping string, integers should be passed without '. Try with:
$sql = 'SELECT region_description FROM ' . $DB_Table . ' WHERE region_id = ' . $region_id . ' AND region_status = 1';
Also ; should be removed.
try this
$sql = "select region_description from $DB_Table where region_id=$region_id AND region_status = 1";
When you are comparing the field of type integer, you should not use single quote
Good Luck
Update 1
Use this.. It will work
$sql = "select region_description from " .$DB_Table. " where region_id=" .$region_id. " AND region_status = 1";
You do not need the single quotes around the region id i.e.
$sql = "SELECT region_description FROM $DB_Table WHERE region_id = $region_id AND region_status = 1"

Categories