Get result of mysql_query inside while of mysql_fetch_array - php

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

Related

Joining two table and updating the result

I am joining two table and I want to update all the rows.
<?php
include("connection/mysqlconnect.php");
$sql=" SELECT course.duration, course.id, students.ID
FROM course, students
where course.id=course_id and course.duration = '2'";
$result = $conn->query($sql);
$count=mysqli_num_rows($result);
if($count>=1)
{
while($row = mysqli_fetch_array($result)) {
$id = $row['ID'];
$stat = 'Active';
$year = '2nd Year';
$Graduated = 'Graduated';
$sql1 = "UPDATE students SET Year='$Graduated', Status='non-Active'
WHERE ID = '$id' and (status='$stat' and Year='$year')";
echo "$id</br>";
}
}
?>
I tried the Select Statement above in "Run SQL query" and it query the result i want. and I want to update all of the query, but I cant. I tried Putting echo under the update and it echo the ID's I need to update, but my update statement is not executing.
Instead of selecting all students then updating one by one, you can actually to this in one shot by joining both tables and updating it.
UPDATE students s
INNER JOIN course c ON c.id = s.course_id
SET s.Year = '$Graduated',
s.Status = 'non-Active'
WHERE c.duration = '2'
AND s.status = '$stat'
AND s.Year = '$year'
It must also be taken into consideration that the query above is vulnerable with sql injection. This article below will guide you how to prevent from it.
How to prevent SQL injection in PHP?
The issue with the first query is that there are two columns with the same name; ID. So referencing the ID from the row generates an error. Use alias to fix it as shown below. For a better performance use an inner join instead. You also forgot to run the update query again your database.
<?php
include("connection/mysqlconnect.php");
$sql=" SELECT course.duration, course.id as cID, students.ID as sID
FROM course JOIN students ON course.id=course_id
where course.duration = '2'";
$result = $conn->query($sql);
$count=mysqli_num_rows($result);
if($count>=1)
{
while($row = mysqli_fetch_array($result)) {
$id = $row['sID'];
$stat = 'Active';
$year = '2nd Year';
$Graduated = 'Graduated';
echo "Student ID to be updated: $id<br/>";
$sql1 = "UPDATE students SET Year='$Graduated', Status='non-Active'
WHERE ID = '$id' and (status='$stat' and Year='$year')";
//you have to execute the query for the update to be done.
if ($conn->query($sql1) === TRUE) {
echo "Record updated successfully ";
} else {
echo "Error updating record: " . $conn->error;
}
}
}
$conn->close();
?>

Echo rows via JOIN in MySQL/PHP (?)

I wanna be able to echo out if Groupname and Username are connected correctly, where the current userid (saved in a session) is $uid.
I've been sitting for hours trying all kinds of JOINs and the closest I've gotten is having it output 1/? members for each team, but not all of them.
EDIT:
$uid = $_SESSION['uid'];
$sql = "SELECT * FROM group
INNER JOIN usergroup ON group.groupid=usergroup.groupid
WHERE usergroup.userid=$uid";
$result=$mysqli->query($sql);
if(mysqli_num_rows($result)>0) {
while($row = mysqli_fetch_array($result)) {
$gid = $row['groupid'];
$sql2 = "SELECT * FROM user
INNER JOIN usergroup ON user.userid=usergroup.userid
WHERE usergroup.groupid=$gid";
$result2=$mysqli->query($sql2);
$row2 = mysqli_fetch_array($result2);
echo "<td>".$row['groupname']."</td>";
echo "<td>".$row2['username']."</td>";
echo "<td>".$row['groupid']."</td>";
}
}
Thing is, that it kinda works well, except that it doesn't print all the groupmembers names out, it prints out just one. Which one seems to depend on the order in the table.
You did not have a loop on the second query's resultset. However, it is not needed to have a second SQL query. Just do it in one go; SQL was designed for that.
Also, you'll have much simpler code:
$uid = $_SESSION['uid'];
// Select everything you need in one go (join user table as well)
$sql = "SELECT group.group_id, group.groupname, user.username
FROM group
INNER JOIN usergroup ON group.groupid=usergroup.groupid
INNER JOIN user ON user.userid=usergroup.userid
WHERE usergroup.userid=$uid";
$result=$mysqli->query($sql);
// Don't need to call mysqli_num_rows if you continue like this:
while($row = mysqli_fetch_array($result)) {
echo "<td>".$row['groupname']."</td>";
echo "<td>".$row['username']."</td>";
echo "<td>".$row['groupid']."</td>";
}
Maybe you want to echo some <tr> and </tr> tags, or you"ll have everything in one row, like:
echo "<tr><td>".$row['groupname']."</td>"
."<td>".$row['username']."</td>"
."<td>".$row['groupid']."</td></tr>";
There you go: (you were missing nested while loop)
if(mysqli_num_rows($result)>0) {
while($row = mysqli_fetch_array($result)) {
$gid = $row['groupid'];
$sql2 = "SELECT * FROM user INNER JOIN usergroup ON user.userid=usergroup.userid WHERE usergroup.groupid=$gid";
$result2=$mysqli->query($sql2);
if(mysqli_num_rows($result2)>0) {
while($row2 = mysqli_fetch_array($result2)) {
echo "<td>".$row['groupname']."</td>";
echo "<td>".$row2['username']."</td>";
echo "<td>".$row['groupid']."</td>";
}
}
}
}
Side note: You could achieve the same results with just one SQL query, something like:
SELECT
*
FROM
usergroup ug
INNER JOIN
user u ON ug.userid = u.userid
GROUP BY
ug.id
and then in PHP (pseudo code just, do not copy-n-paste)
while($row => mysqli_fetch_array($result)) {
if (!isset($groupsWithUsers[$row['groupid']['users'])) {
$groupsWithUsers[$row['groupid']['users'] = array()
}
$groupsWithUsers[$row['groupid']['users'][$row['userid']] = $row;
}

Pulling Joined Table Data Before WHILE

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);

Getting the table name of a row from a mysql query that grabs from multiple tables

I have some PHP/MySQL code that pulls data from multiple different tables (using Inner Joins). It looks something like this:
$query = "SELECT * FROM table1 INNER JOIN table2 USING (key)";
$data = mysqli_query($dbc, $query);
while ($row = mysqli_fetch_array($data)) {
echo $row[1];
}
So the code is simple enough, but what I want to do is echo the table each row is in inside of that while loop, since it could be in one of 2 tables.
I saw there was some old mysql functions like mysql_field_table and mysql_tablename that would do the trick, but they all seem to be deprecated.
Would appreciate any advice on how to accomplish this.
You could select the data with a special identifier for each table instead of using *
select table1.row1 as t1r1, table2.row1 as t2r1,..... from .....
And inside php you could look for the strings t1 and t2 and do stuff accordingly.
What you can do is echo more than one field from your result table (which hopefully now contains information from both the tables.
$query = "SELECT * FROM table1 INNER JOIN table2 USING (key)";
$data = mysqli_query($dbc, $query);
while ($row = mysqli_fetch_array($data))
{
echo $row[1] . " " . $row[2];
}
...and then $row[3] etc...
Or access the column name/field by the column name or alias provided by AS.
$query = "SELECT * FROM table1 INNER JOIN table2 USING (key)";
$data = mysqli_query($dbc, $query);
while ($row = mysqli_fetch_assoc($data))
{
echo $row["c_name1"] . " " . $row["c_name2"];
}
Where "c_name1" and "c_name2" are your column names.
Use an AS keyword to rename all columns.
$select_clause = '';
$tables = array('tblA', 'tblB');
foreach($tables as $tbl) {
mysql_query('SHOW COLUMNS FROM ' . $tbl);
while ($row = mysql_fetch_assoc())
$select_clause .= '`'.$tbl.'`.`'.$row['Field'].'` AS `'.$tbl
.'_'.$row['Field'].'`,';
}
$select_clause = substr($select_clause, 0, -1);
mysql_query('SELECT '.$select_clause.' FROM /*...*/ ');

loop problem within a statement

i hope someone can help about to scream!
basically I am trying to do a few things with the statement below;
First i want to check if the user id exists in member_categories_position.
If it Does i want then to exclude all entries from the second statement where member_id equals all results from the first statement
the third statement is the else statement that displays if the member_id is not present in the member_categories position.
PROBLEM - the result from the first system loops fine, however when i try and insert into the second statement (!='$memid') is produces no results and has no effect. I think the problem is that $memid is a looped result.
How do i get the second statement to say that any member_id that is in member_categories_position will not show in that statement?
$sql2 = "
SELECT *
FROM member_categories_position a
JOIN member_users b
ON b.id = a.member_id";
$rs2 = mysql_query($sql2);
while ($row = mysql_fetch_array($rs2))
{
$memid = "".$row['member_id']."";
}
if(mysql_num_rows($rs2) != 0)
{
$new= "
SELECT *
FROM member_categories
JOIN member_users
ON member_categories.member_id=member_users.id
JOIN member_config
ON member_categories.member_id=member_config.member_id
WHERE
member_categories.categories='$category'
AND member_categories.member_id !='$field'
GROUP BY member_config.member_id
ORDER BY RAND() limit 0,42";
$rs = mysql_query($new);
while ($row = mysql_fetch_assoc($rs))
{
echo "result excluding member ids from the first statement";
}
echo "<div class=\"clear\"></div>";
}
else
{
$new= "
SELECT *
FROM member_categories
JOIN member_users
ON member_categories.member_id=member_users.id
JOIN member_config
ON member_categories.member_id=member_config.member_id
WHERE
member_categories.categories='$category'
GROUP BY member_config.member_id
ORDER BY RAND() limit 0,42";
$rs = mysql_query($new);
while ($row = mysql_fetch_assoc($rs))
{
echo "Result with all member ids";
}
echo "<div class=\"clear\"></div>";
} } <-- (second is a stray from original post)
$memid is not in scope since it appears to be defined inside the loop. Try defining $memid = ''; at the top of your script.. like this.
$memid = '';
$sql2 = "
SELECT *
That way it will be defined when you use it below..

Categories