2 while loops in php - mysql select statement - php

I have 2 tables in DB:
clients (Show all clients data)
clientsmany (admin could add many phone numbers for each client)
I would like to print all the details about the clients in 1 html table and if any client has more than phone number, all the numbers are printed in the same cell of 'td'
<?php
$result = mysql_query("SELECT * FROM clients");
$result1 = mysql_query("SELECT clientsmany.phone, clients.ID FROM clients INNER JOIN clientsmany ON clients.ID=clientsmany.ClientID");
while($row = mysql_fetch_array($result)){ //Not read!
while($row1 = mysql_fetch_array($result1)){ //Working correctly and show the list of 'phone' in $row1 for clientsmany.phone
echo "<center><table border='1'>";
echo "<tr><td>".$row['ID']."</td><td>".$row['phone']."<br>".$row1['phone']."</td></tr>";
echo "</table></center>";
}}
?>
Why the 1st while is not working??
The 2nd while only works and print a correct data then it exit automatic!

<?php
echo "<center><table border='1'>";
$result = mysql_query("SELECT * FROM clients");
while($row = mysql_fetch_array($result)){
$result1 = mysql_query("SELECT * FROM clientsmany WHERE clientsid=".$row['id']);
if(mysql_num_rows($result1)>0 ){
while($row1 = mysql_fetch_array($result1)){
echo "<tr><td>".$row['ID']."</td><td>".$row['phone']."<br>".$row1['phone']."</td> </tr>";
}
}else{
echo "<tr><td>".$row['ID']."</td><td>".$row['phone']."</td></tr>";
}
}
echo "</table></center>";
?>

Use GROUP_CONCAT to create a single query and you will be able to a single loop
GROUP_CONCAT will take a column that is repeated and separate each value with a comma (by default it can be changed) and return it into a single value
$query = <<<END
SELECT
clients.*,
GROUP_CONCAT(clientsmany.phone) as phonenums
FROM
clients
INNER JOIN
clientsmany ON clients.ID=clientsmany.ClientID
GROUP BY
clients.ID
END;
A query like this would give you all the clients table columns and a column named phonenums which will be a comma separated list of the phone numbers
Now since you only have one query you only need one loop
$db = mysqli_connect(...);
...
//only need to echo out the <table> part once
//so taken out of the while loop
echo "<center><table border='1'>";
$result = mysqli_query($db,$query);
while( ($row = mysqli_fetch_assoc($result)) ) {
echo <<<END
<tr>
<td>{$row['ID']}</td>
<td>{$row['SomeOtherColumn']}</td>
<td>{$row['phonenums']}</td>
</tr>
END;
}
//Again the </table> only needs done once
//so taken out of the loop
echo "</table></center>";
Notice the mysli_* functions being used. Mysql api is depreciated, for the most part you can just rename the functions you currently use to mysqli_, but note that some require the $db link as a parameter so make sure to read the php manual on each of the functions so you know how to call them correctly.
Also note that I am using heredoc syntax instead of doing multiple echo calls

First, mysql_* functions are depreciated. Try to use mysqli_* functions.
If you want to display data in 1 html table, so why you have started while above table tag?
Try this query..
SELECT clientsmany.phone, clients.* FROM clients, clientsmany WHERE clients.ID=clientsmany.ClientID"
Then use while statement below table tag (No need of 2 different while loop)...
echo "<center><table border='1'>";
while($row1 = mysqli_fetch_array($result1)) {
// your <tr><td> code
}
echo "</table></center>";

Related

I am having issues with parsing a variable from an SQL into another SQL statement with PHP

<?php
if(isset($_POST['submitted'])){
//Connecting to the database
include('includes/connection.php');
// Creating variables to Post selected input item into database
$meeting_type = explode('|', $_POST['meeting_type']);
$date_picker = $_POST['date_picker'];
//$query = "SELECT * FROM meeting_tb WHERE meeting_type = '$meeting_type[1]'";
$query = "SELECT meeting_id, meeting_type, date FROM meeting_tb WHERE date in (select Max(date) as mindate from meeting_tb where meeting_type = '$meeting_type[1]')";
$query_result = mysqli_query($db_con, $query) or die("error retrieving data");
$row_meeting = mysqli_fetch_array($query_result, MYSQLI_ASSOC) or die("Not able to retrieve information");
$query_item = "SELECT join_tb.item_id, item_name, item_description FROM join_tb INNER JOIN meeting_item_tb ON join_tb.item_id = meeting_item_tb.item_id WHERE join_tb.meeting_id = '$row_meeting[meeting_id]'";
$result = mysqli_query($db_con, $query_item) or die("error retrieving data");
echo "<table>";
echo "<tr> <th>ITEM ID</th> <th>ITEM NAME</th> <th>ITEM DESCRIPTION</th> </tr>";
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
echo "<tr><td>";
echo $row['item_id'];
echo "</td><td>";
echo $row['item_name'];
echo "</td><td>";
echo $row['item_description'];
echo "</td></tr>";
}
echo "</table>";
}
//End of IF statement
?>
The Issue involves the use of $row_meeting[meeting_id] in the second select statement. If I put a numeric value in place of $row_meeting[meeting_id], the select statement works and it displays an output on the browser. But if I use $row_meeting[meeting_id] in the second select statement, it does not get the data from the database
By putting single inverted commas around $row_meeting[meeting_id], you are converting the number to a string when parsing it to SQL. To avoid parsing it to as string you can simply remove the single inverted commas. So your select statement will look like:
$query_item = "SELECT join_tb.item_id, item_name, item_description FROM join_tb INNER JOIN meeting_item_tb ON join_tb.item_id = meeting_item_tb.item_id WHERE join_tb.meeting_id = $row_meeting['meeting_id']";
Hope this helps.
Try this in your second query
$query_item = "SELECT join_tb.item_id, item_name, item_description FROM join_tb INNER JOIN meeting_item_tb ON join_tb.item_id = meeting_item_tb.item_id WHERE join_tb.meeting_id = ".$row_meeting[meeting_id].";";
It is possible because of the single quoted around the variable.

How to show all data one after another from mysql_fetch_array() in php

$sql="SELECT userId FROM eventmember WHERE eventid='$event_id';";`
$resultset = mysql_query($sql);
$row = mysql_fetch_array($resultset);
I got specific userid from specific event column like eventid==> eid-01(us-0, us-3,...),
$num_row = mysql_num_rows($resultset);
while($row) {
for($i = 0; $i<$num_row; $i++) {
$sql = "SELECT userId, firstName FROM userinfo WHERE userId='$row[$i]';";
$resultset = mysql_query($sql);
$row22 = mysql_fetch_array($resultset);
$us_id = $row22['userId'];
$us_name = $row22['firstName'];
echo "<tr>";
echo "<td>ID:</td> <td class='text2' align='center' colspan='2'>
<b> $us_id </b>
</u></td>";
echo "</tr>";
break;
}
$row = mysql_fetch_array($resultset);
}
On that code I got only one userid info but there is more userid against one event.
First of all, use if statement to check whether the returned result set contains any row or not, like this:
if($num_row){
// your code
}
Second, use a while loop to loop through the result set and display it's contents, like this:
while($row22 = mysql_fetch_array($resultset)){
// your code
}
And finally, please don't use mysql_ database extensions, they were deprecated in PHP 5.5.0 and were removed in PHP 7.0.0. Use mysqli or PDO extensions instead. And this is why you shouldn't use mysql_ functions.
So your code should be like this:
<?php
$sql="SELECT userId FROM eventmember WHERE eventid='$event_id'";
$resultset = mysql_query($sql);
$row = mysql_fetch_array($resultset);
$num_row = mysql_num_rows($resultset);
if($num_row){
$sql = "SELECT userId, firstName FROM userinfo WHERE userId='" . $row['userId'] . "'";
$resultset = mysql_query($sql);
?>
<table>
<tr>
<td>User ID</td>
<td>First Name</td>
</tr>
<?php
while($row22 = mysql_fetch_array($resultset)){
echo "<tr><td>{$row22['userId']}</td><td>{$row22['firstName']}</td></tr>";
}
?>
</table>
<?php
}
?>
For better readability I have displayed the data in table cells.
Simple Solution
You need to get multiple userIds from eventmember table which have multiple users against each event. But you are fetching only once from that query with $row = mysql_fetch_array($resultset);, So you should get only one user, what you are getting now. Hence, the problem is, you actually have put the while loop in a wrong place. The loop should be set like this :
$sql="SELECT userId FROM eventmember WHERE eventid='$event_id';";
$resultset = mysql_query($sql);
$num_row = mysql_num_rows($resultset);
if($num_row) {
while($row = mysql_fetch_array($resultset)) {
$sql22 = "SELECT userId, firstName FROM userinfo WHERE userId='{$row['userId']}';";
$resultset22 = mysql_query($sql22);
$row22 = mysql_fetch_array($resultset22);
$us_id = $row22['userId'];
$us_name = $row22['firstName'];
echo "<tr>";
echo "<td>ID:</td> <td class='text2' align='center' colspan='2'>
<b> $us_id </b>
</u></td>";
echo "</tr>";
//You shouldn't use a break here. This will again give you single result only.
}
}
A Better Solution
Instead of using multiple queries to get the data from userinfo table, use JOIN to get all data with one query. Like this :
$sql="SELECT u.userId,u.firstName FROM eventmember e JOIN userinfo u ON u.userId = e.userId WHERE e.eventid='$event_id';";
$resultset = mysql_query($sql);
$num_row = mysql_num_rows($resultset);
if($num_row) {
while($row = mysql_fetch_array($resultset)) {
$us_id = $row['userId'];
$us_name = $row['firstName'];
echo "<tr>";
echo "<td>ID:</td> <td class='text2' align='center' colspan='2'>
<b> $us_id </b>
</u></td>";
echo "</tr>";
}
}
The Best and Most Secure Solution
As you should have already known mysql_* functions are removed in PHP 7 and this functions are highly harmful for your security. So, you should either move to PDO or mysqli_* functions. I am giving here an example with mysqli_* functions and additionally I am fetching all rows at once instead of doing fetch for each row, which is better for performance.
//First setup your connection by this way.
$link = mysqli_connect(localhost, "my_user", "my_password", "my_db");
//Now you can use mysqli
$sql="SELECT u.userId,u.firstName FROM eventmember e JOIN userinfo u ON u.userId = e.userId WHERE e.eventid=?;";
$stmt = mysqli_prepare($link, $sql);
$stmt->bind_param('s', $event_id);
$stmt->execute();
$resultset = $stmt->get_result();
$resultArray = $resultset->fetch_all();
$num_row = count($resultArray);
if($num_row) {
foreach($resultArray as $row) {
$us_id = $row['userId'];
$us_name = $row['firstName'];
echo "<tr>";
echo "<td>ID:</td> <td class='text2' align='center' colspan='2'>
<b> $us_id </b>
</u></td>";
echo "</tr>";
}
}
mysql_fetch_array() will retrieve a single result from a result set. Therefore you'll need to wrap it in a loop to get each row/result.
Here's an example I ripped straight from the PHP documentation:
while ($row = mysql_fetch_array($result)) {
printf("ID: %s Name: %s", $row["id"], $row["name"]);
}
In your case you'd wrap the HTML code in the while loop.
An additional improvement would be to ensure that $resultset is a resource; mysql_query() can return false if your query is invalid (and true in other success cases like INSERTS). You can also use mysql_num_rows() to determine if you have >0 rows to display (and custom display a 'No rows returned' message).
Perhaps more importantly is that mysql_* functions were deprecated in PHP 5.5.0, and additionally removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL.
By continuing to write mysql_ code you'll make upgrading substantially more difficult for yourself. It's also worth noting that 5.5 will also reach security EOL in 6 months, leaving you to rely on your OS vendor to backport security updates from then on.

Display count of unique values in MySQL db table using PHP

So I have a table named pins that has 3 columns that need to be taken into consideration. These columns are plan and order_id.
I need to get a count for all of the pins that have an order_id=0 and plan=9.
This is what I have so far:
$qT="SELECT plan, COUNT(*) as cnt FROM pins WHERE order_id=0 and plan=9";
$res=mysql_query($qT);<br/>
mysql_free_result($res);
while($row = mysql_fetch_array($res)) {<br/>
echo $row['plan'];<br/>
}
Any help in displaying the results would be a great help.
Try to group your pin using GROUP BY, So
$result = mysql_query("SELECT plan, COUNT(pin) as cnt FROM pins WHERE (order_id=0 and plan=9) GROUP BY plan");
echo "<table border='1' style='border-collapse: collapse'>";
echo "<th>Plan</th><th>Count</th>";
while ($row = mysql_fetch_array($result))
{
echo "<tr><td>".$row['plan']."</td><td>".$row['cnt']."</td></tr>";
}
echo "</table>";
mysql_free_result($result);
?>

Mysqli query multiple tables

I'm trying to make a query that then displays certain results based on previous queries
The idea is that when someone logs into the page, it gets the session username and and saves it to a variable, from there the first query selects a row based on the session username, gets that value and does the same in the second query but on a different table this time getting the row based on the result from query 1 and query 3 is same as two and then its meant to echo it out
here's the code
$con = mysqli_connect("localhost","root","","boats4u");
$search = $_SESSION['myusername'];
if(mysqli_connect_errno())
{
echo "Failed to connect to database". mysqli_connect_error();
}
$pre_res = mysqli_query($con,"SELECT ownerNo FROM boatowner WHERE email ='$search'");
$pre_res = $pre_res -> fetch_assoc();
$result = mysqli_query($con,"SELECT boatNo FROM boatforrent WHERE ownerNo ='$pre_res'");
$result = $result -> fetch_assoc();
$result2 = mysqli_query($con,"SELECT * FROM boatviewing WHERE boatNo = '$result'");
echo "<table border='1'>
<tr>
<th>Client No</th>
<th>Boat No</th>
<th>View Date</th>
<th>Comments</th>
</tr>";
while ($row = mysqli_fetch_array($result2))
{
echo "<tr>";
echo "<td>". $row['clientNo']."</td>";
echo "<td>". $row['boatNo']."</td>";
echo "<td>". $row['viewDate']."</td>";
echo "<td>". $row['comment']."</td>";
}
echo "</table>";
?>
this is what displays
Notice: Array to string conversion in
E:\Download\Xampp\htdocs\owner.php on line 29
If I remove the first query then it no errors but obviously the search doesn't work then
any help appreciated
You should do one query and also parametize the search parameter. Something along the lines like:
$stmt = $con->prepare('
SELECT boatviewing.*
FROM boatowner owner
LEFT JOIN boatforrent ON boatforrent.ownerNo = owner.ownerNo
LEFT JOIN boatviewing ON boatviewing.boatNo = boatforrent.boatNo
WHERE owner.email = ?
');
$stmt->bind_param("s", $search);
$stmt->execute();
$result = $stmt->get_result();
Such code is normally more robust against SQL injection and it's also easier in case you change your database layout.
Next to that you actually run one query instead of three which allows the database to optimize data-retrieval and keeps roundtrips between the PHP script and the database server low.

Displaying items from multiple tables on your webpage using php while loop

I am trying to dsiplay data from 2 different tables from my mysql database using a while loop.
Currently I can display the data from 1 table and limit the results to 3. I then want to display the first 5 records from another table. If I join the tables I can only display the same number of items from both using LIMIT?
I am using a while loop to display the content from a table called item, using the following code;
$query");
$result2 = #mysql_query($query, $connection)
or die ("Unable to perform query$query");
<?php
while($row= mysql_fetch_array($result))
{
?>
<?php echo $row['item'] ?>
<?php
}
?>
If I start another loop for the data from the next table called movie, however the data is not displayed using the following code;
<?php
while($row= mysql_fetch_array($result2))
{
?>
<?php echo $row['title'] ?>
<?php
}
?>
What is the best way to display the data from the 2 tables?
Many Thanks
I don't know if you forgot to paste a bit of code, but this should work:
<?php
$query = "select * from item order by date, time asc limit 0,3";
$result = mysql_query($query);
while($row= mysql_fetch_array($result))
{
echo $row['item'];
}
$query2 = "select * from movie limit 0,5";
$result2 = mysql_query($query2);
while($row= mysql_fetch_array($result2))
{
echo $row['movie'];
}
?>
You may be able to do it with one SQL Query too:
SELECT i.item, m.movie
FROM (SELECT * FROM item ORDER BY date, time ASC LIMIT 0,3) i,
(SELECT * FROM movie limit 0,5) m
Then in php:
<?php
while($row= mysql_fetch_array($result))
{
echo $row['item'];
echo $row['movie'];
}
?>
But that depends on how you want to format the output.

Categories