Pulling Joined Table Data Before WHILE - php

I am VERY new at MySQL and PHP writing. What I am having problems with is pulling data from specific tables, BEFORE the while line. My current code is
$query_join_tables = "SELECT m.*, c.id, c.firstname, c.lastname,
IFNULL(m.system_customer,c.id) AS client_id
FROM ... AS m
LEFT
JOIN ... as c
ON m.system_customer = c.id
WHERE system_customer=".$clientid."
ORDER BY system_id ASC";
$result = mysql_query($query_join_tables);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
echo "BLA BLA BLA";
while($row = mysql_fetch_array($result)){
echo "MORE BLA BLA";
The problem is when I attempt to pull from the table BEFORE the while line it won't pull. If I pull after, it works just fine.
Does not work:
echo ".$row['firstname'].";
while($row = mysql_fetch_array($result)){
Does work:
while($row = mysql_fetch_array($result)){
echo ".$row['firstname'].";
Also, before mysqli or PDO are mentioned - I cannot do it. I'm writing a module for something that is encrypted and hard coded.

You will feel silly. The $row variable has not been given the fetched rows yet. when the line
$row = mysql_fetch_array($result)
is run, that is when ONE row's data is given to $row. Calling $row before this point will only give you a null value.
Each time the while loop starts again, it gets a new row. This is called an ITERATOR. It moves down the list one row at a time until it runs and finds nothing. That is when it will exit the loop.
EDIT (01/23/2015): Now that I understand that you actually want to have two loops use the same result. I will show how to reset the iterator.
while($row = mysql_fetch_array($result)) {Do Stuff}
mysql_data_seek($result, 0);
while($row = mysql_fetch_array($result)) {Do Stuff}
Hope this helps.

The mysql extension is deprecated and will be removed in the future. Use mysqli. Try following code.
$con = mysqli_connect("localhost","root","","dbname");
$query_join_tables = "SELECT m.*, c.id, c.firstname, c.lastname,
IFNULL(m.system_customer,c.id) AS client_id
FROM ... AS m
LEFT
JOIN ... as c
ON m.system_customer = c.id
WHERE system_customer=".$clientid."
ORDER BY system_id ASC";
$result = $con->query($query_join_tables);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
echo $row["firstname"];
$conn->close();

Okay, Simply try this. It should work.
mysql_connect("localhost", "root", "") or
die("Could not connect: " . mysql_error());
mysql_select_db("dbName");
$query_join_tables = "SELECT m.*, c.id, c.firstname, c.lastname,
IFNULL(m.system_customer,c.id) AS client_id
FROM ... AS m
LEFT
JOIN ... as c
ON m.system_customer = c.id
WHERE system_customer=".$clientid."
ORDER BY system_id ASC";
$result = mysql_query($query_join_tables);
$res = mysql_fetch_array($result);
echo $res['vBookName'];
mysql_free_result($result);

Related

Problems getting my info from table join to display in PHP

{Connecting 2 tables together (with teacher ID and teacher name)
I have created the join and I have tested in SQL. Seems good. I am trying to print it on the screen.
$classandteacher = "SELECT person_name FROM people RIGHT OUTER JOIN classes ON classes.instructor_id=people.instructor_id ASC";
$result = mysqli_query($dbc, $classandteacher){
while($row = mysqli_query($dbc, $result));
$teacher = $row["person_name"];
echo ("Teacher: " . $teacher . "<br>");}
It's because the While Loop isn't correctly formatted.
Remove the ; and put it into {}
You also need to use mysqli_fetch_assoc($result) to get the Array from the query
$classandteacher = "SELECT person_name FROM people RIGHT OUTER JOIN classes ON classes.instructor_id=people.instructor_id ASC";
$result = mysqli_query($dbc, $classandteacher);
if(!$result) { //If your MYSQL query is throwing an error
error_log(mysqli_error());
}
while($row = mysqli_fetch_assoc($result))
{
$teacher = $row["person_name"];
echo "Teacher: " . $teacher . "<br>";
}
Or try using
mysqli_fetch_array instead
$classandteacher =
"SELECT
person_name FROM
people RIGHT OUTER JOIN classes ON
classes.instructor_id
=
peopleinstructor_id ASC";
$result =
mysqli_query($dbc,$ classandteacher);
if(!$result) { //If
your MYSQL query is
throwing an error
error_log(mysqli_er
ror() );}
while($row =
mysqli_fetch_array(
$result))
{
$teacher = $row
["person_name"];
echo "Teacher: " . $
teacher . "<br>"; }

Accessing rows from a mysqli join query in php

I have the following code:
// db connection info set up earlier
$sql= "SELECT `TABLE_1.ID`, `TABLE_2.ID`, `POTATO` FROM `TABLE_1.ID` LEFT JOIN `TABLE_2` ON `TABLE_1`.`ID` = `TABLE_2`.`ID_OF_OTHER_TABLE`;";
$rows = mysqli_query($connection, $sql);
foreach ($rows as $row){
$potato = $row["POTATO"];
$id = $row["TABLE_2.ID"];
}
I can't get TABLE_2.ID. I've tried to doing a print_r to get the proper format, but it says it's a mysqli object and I don't get much more info than that. However, I can get potato. So I'm guessing it's a calling syntax issue, but I've searched multiple sites (stack and google included) and not found a clear answer. So, what do I need to do instead of
$id = $row["TABLE_2.ID"];
?
Assign aliases to the columns with the same name.
$sql= "SELECT `TABLE_1`.`ID` AS t1_id, `TABLE_2`.`ID` AS t2_id, `POTATO`
FROM `TABLE_1.ID`
LEFT JOIN `TABLE_2` ON `TABLE_2`.`ID_OF_OTHER_TABLE` = `TABLE_1`.`ID`;";
$rows = mysqli_query($connection, $sql);
foreach ($rows as $row){
$potato = $row["POTATO"];
$id = $row["t2_id"];
}
You can't left join a table with itself, you also cannot have a table that isn't joined = something from another table that cannot be joined to itself.
This will work:
// db connection info set up earlier
$sql= "SELECT TABLE_1.ID, TABLE_2.ID, POTATO
FROM
TABLE_1.ID
LEFT JOIN TABLE_2 ON TABLE_1.ID = TABLE_2.ID";
$rows = mysqli_query($connection, $sql);
while ($row = mysqli_fetch_assoc($rows)) {
echo ($row['ID']);
}
mysql_free_result($rows);

Get result of mysql_query inside while of mysql_fetch_array

I am using a code something like below to get data from the second table by matching the id of first table. Code is working well, but I know it slow down the performance, I am a new bee. Please help me to do the same by an easy and correct way.
<?php
$result1 = mysql_query("SELECT * FROM table1 ") or die(mysql_error());
while($row1 = mysql_fetch_array( $result1 ))
{
$tab1_id = $row1['tab1_id'];
echo $row['tab1_col1'] . "-";
$result2 = mysql_query("SELECT * FROM table2 WHERE tab2_col1='$tab1_id' ") or die(mysql_error());
while( $row2 = mysql_fetch_array( $result2 ))
{
echo $row2['tab2_col2'] . "-";
echo $row2['tab2_col3'] . "</br>";
}
}
?>
You can join the two tables and process the result in a single loop. You will need some extra logic to check if the id of table1 changes, because you'll only want to output this value when there's a different id:
<?php
// Join the tables and make sure to order by the id of table1.
$result1 = mysql_query("
SELECT
*
FROM
table1 t1
LEFT JOIN table2 t2 ON t2.col1 = t1.id
ORDER BY
t1.id") or die(mysql_error());
// A variable to remember the previous id on each iteration.
$previous_tab1_id = null;
while($row = mysql_fetch_array( $result1 ))
{
$tab1_id = $row['tab1_id'];
// Only output the 'header' if there is a different id for table1.
if ($tab1_id !== $previous_tab1_id)
{
$previous_tab1_id = $tab1_id;
echo $row['tab1_col1'] . "-";
}
// Only output details if there are details. There will still be a record
// for table1 if there are no details in table2, because of the LEFT JOIN
// If you don't want that, you can use INNER JOIN instead, and you won't need
// the 'if' below.
if ($row['tab2_col1'] !== null) {
echo $row['tab2_col2'] . "-";
echo $row['tab2_col3'] . "</br>";
}
}
Instead of having 2 while loops, what you can do is join the 2 tables and then iterate over the result.
If you're not sure what join is look here: https://dev.mysql.com/doc/refman/5.1/de/join.html
Also here is a fairly simple query written using join: Join Query Example
You can use this. One relation with two tables:
<?php
$result1 = mysql_query("SELECT tab2_col2, tab2_col3 FROM table1, table2 where tab2_col1 = tab1_id ") or die(mysql_error());
while($row1 = mysql_fetch_array( $result1 ),)
{
echo $row2['tab2_col2'] . "-";
echo $row2['tab2_col3'] . "</br>";
}
?>
Like Sushant said, it would be better to use one JOIN or simpler something like that:
SELECT * FROM table1, table2 WHERE `table1`.`id` = `table2`.`id

Can I randomly select a row from one table and use a static identifier to select corresponding data in another table?

The following script was initially intended to select a row at random, which it could do fine, however, I an unable to figure out how to amend it to select data from a second table using a column ID called "nid" which is the same in both tables:
$conn = mysqli_connect($host,$username,$password, $database) or die(mysql_error ());
$total_rows = 5;
$selected_row = mt_rand(0, $total_rows);
$query="SELECT * FROM `node` LIMIT $selected_row, 1;";
$result=$conn->query($query);
while($row = $result->fetch_assoc()) {
$node=$row["nid"];
echo $row["title"];
$query2="SELECT * FROM `field_data_body` LIMIT $node, 1;";
$result2=$conn->query($query2);
while($row = $result->fetch_assoc()) {
echo $row["body_value"];
}
Admittedly, the above is not really close to working, but I was hardpressed to find an example of what I was after.
These tables are in the database for a Drupal site, so the title field and the body_value fields are in two different tables; ultimately, I would like to echo a result that is a matching set of title and body_value for a randomly selected node.
Speaking of this script specifically, I want to use the nid to find the corresponding row for the second table.
Is this possible?
The bit that works, selecting the data I want from a single table is in the following format:
$total_rows = 5;
$selected_row = mt_rand(0, $total_rows);
$query="SELECT * FROM `field_data_body` LIMIT $selected_row, 1;";
$result=$conn->query($query);
while($row = $result->fetch_assoc()) {
echo $row["body_value"];
}
?>
UPDATE:
At the suggestion of a commenter, I used a join, and ended up with:
$conn = mysqli_connect($host,$username,$password, $database) or die(mysql_error ());
$total_rows = 5;
$selected_row = mt_rand(0, $total_rows);
//Use the result in your limit.
$query="SELECT a.nid, a.title, b.entity_id, b.body_value
FROM node a, field_data_body b
WHERE a.nid = b.entity_id LIMIT $selected_row, 1;";
$result=$conn->query($query);
while($row = $result->fetch_assoc()) {
echo $row["title"];
echo " | ";
echo $row["body_value"];
}
which worked perfectly.
for future reference since you have solved your problem, you need to close the previous connection before starting a new one, or free the results
$conn = mysqli_connect($host,$username,$password, $database) or die(mysql_error ());
$total_rows = 5;
$selected_row = mt_rand(0, $total_rows);
$query="SELECT * FROM `node` LIMIT $selected_row, 1;";
$result=$conn->query($query);
while($row = $result->fetch_assoc()) {
$node=$row["nid"];
echo $row["title"];
$result->close(); // close $result
$query2="SELECT * FROM `field_data_body` LIMIT $node, 1;";
$result2=$conn->query($query2);
while($row = $result->fetch_assoc()) {
echo $row["body_value"];
}
$result2->close(); // close $result2
i also notice you haven't closed the connection on the UPDATE you posted either which will lead you to run into the same problem again later on.
If this is just about to select a single record, you do not have to define the LIMIT, instead you can use the randomly generated value to select the row by using it in WHERE!
You can just join the two tables. Beside that, your code has a potential problem. It relies on the existence of at least 5 records. You can avoid that by putting the randomization into the query. The code will then be
$conn = mysqli_connect($host,$username,$password, $database) or die(mysql_error());
$query = "SELECT n.*, b.* FROM `node` AS n LEFT JOIN `field_data_body` AS b ON n.nid=b.nid ORDER BY REVERSE(RAND()) LIMIT 0, 1;";
$result = $conn->query($query);
$row = $result->fetch_assoc();
$result->close();
echo $row["title"];
echo $row["body_value"];
The REVERSE() function makes the result from RAND() more random. You may omit it, if you want.

PHP query multiple Tables

I'm having trouble getting any information to display from this query. Anyone know where I'm going wrong?
Thank you!
$query = "SELECT * ".
"FROM comments, users ".
"WHERE comments.user_id = users.user_id ".
"ORDER BY comments.date DESC ".
"LIMIT 10";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
echo $row['users.user_id'];
echo $row['comments.comment'];
}
use mysql_fetch_assoc() instead of mysql_fetch_array().
In your loop use the column name as the array key:
while ($row = mysql_fetch_assoc($result)) {
echo $row['column_name1'];
echo $row['column_name1'];
}
In your query try to be more specific on the select statement, try not to use *.
You're probably getting the error because you are sorting (ORDER BY) on a field that does not exist in your query.
It would be best practice to not use the "SELECT *" querying. If all you need are specific values, specify them. This also helps when retrieving the data...
$query = "SELECT users.user_id, comments.comment, comments.date ".
"FROM comments, users ".
"WHERE comments.user_id = users.user_id ".
"ORDER BY comments.date DESC ".
"LIMIT 10";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
echo $row['user_id'];
echo $row['comment'];
echo $row['date'];
}
It is good practice to specify column names in a query rather than using * - on some DBs there is a performance impact and on all it prevents any unexpected behaviour cropping up from table changes.
In the example I think the issue is arsing from the array keys you are using - you don't need to include the table name in them, just the column name:
echo $row['user_id'];
echo $row['comment'];
The better practice is to write only fields what you need in your sql query like this:
$query = "SELECT u.user_id uid, c.comment comment ".
"FROM comments c, users u ".
"WHERE comments.user_id = users.user_id ".
"ORDER BY comments.date DESC ".
"LIMIT 10";
Using so type of queries you reduce the time of executing your query and transmitting data from database server to your php script. After this modification your cycle transformed to:
while ($row = mysql_fetch_array($result)) {
echo $row['uid'], $row['comment'];
}
I use PDO method but this can work for you too:
<?php
$sql = "SELECT * FROM comments as c INNER JOIN users as u ON c.user_id=u.user_id WHERE u.user_id=:user_id ORDER BY c.date DESC LIMIT 10";
//prepare the connection to database
$prep = $conn->prepare($sql);
//change the parameters for user_id on WHERE condition you can put anything you want but i will put the user session id
$prep->bindParam(":user_id", $_SESSION['user_id']);
$prep->execute();
//ill use fetchAll function because it can be more than 1 comment
$datas = $prep->fetchAll();
foreach($datas as $data){
echo $data['user_id'];
echo $data['comment'];
echo $data['date'];
}
?>

Categories