php mysql query whitin While loop - php

I have a Mysql table which is use in php, first I use while loop to fetched the rows that as below
$q1 = "SELECT * FROM same_table WHERE `t_type`=1 AND `status`=0 AND `accept`='0'";
while($row1 = $q1->fetch_assoc()){
...table to output records
echo '<tr>
<td>$row1['col1']</td>
<td>$row1['col2']</td>
</tr>';
}
this will come out necessary records successfully.
secondly, there is another row with different purpose located under each of the above query row if the condition is true, with same table (within while loop),
while($row1 = $q1->fetch_assoc()){
echo '<tr>
<td>$row1['col1']</td>
<td>$row1['col2']</td>
</tr>';
$q2 = "SELECT * FROM same_table WHERE `t_type`=1 AND `status`=0 AND `bonus_accept`='0'";
$row2 = $q2->fetch_assoc();
if(($row2['col3'] == true){
echo '<tr>
<td>$row2['col1']</td>
<td>$row2['col2']</td>
</tr>';
}
}
so far the $q2 rows is show but always repeat the first record's data only even there is several row for $q1. if the data for $row2['col1'] is 100, the rest all show 100.
Please kindly help.

Related

calculations on specific rows in table of database using php

i'm working on a php project that manages teachers in school. but i'm stuck with a problem, i have two tables in my database, first one T1 has on row, second T2 has multiple rows, but they have the same columns number. in a third table T3 i need to fill a column with the total of
(cell1 of T1*cell1 of T2) + (cell2 of T1*cell2 of T2)+ (cell3 of T1*cell3 of T2)....to the last column
i just couldn't find the right way to do this
this is the part that shows the tables from my db
<?php
$host="localhost";
$user="root";
$pass="";
$bdd="test";
$cnx=mysql_connect($host,$user,$pass);
if(!$cnx)
echo"connexion echouee"."</br>";
else
echo"connexion reussie"."</br>";
if (mysql_select_db($bdd))
echo"base de donnees trouvee"."</br>";
else
echo"base de donnees introuvable"."</br>";
$req1="SELECT * FROM `table1`";
$res1=mysql_query("$req1");
// printing table rows
while($row1 = mysql_fetch_row($res1))
{
echo "<tr>";
foreach($row1 as $cell1)
echo "<td>|$cell1|</td>";
echo "</tr>"; echo"</br>";
}
echo "_____</br>";
$req2="SELECT * FROM `table2`";
$res2=mysql_query("$req2");
// printing table rows
while($row2 = mysql_fetch_row($res2))
{
echo "<tr>";
foreach($row2 as $cell2)
echo "<td>|$cell2|</td>";
echo "</tr>";echo"</br>";
}
?>
As long as it is guaranteed that table1 will return 1 row, here is a suggestion:
Instead of using a while loop to fetch the contents, just fetch the row, so the contents of table1 are in $row1
Change foreach($row2 as $cell2) to a foreach($row2 as $key=>$value) format. This way you will have the index of the corresponding element in $row1
Inside the foreach($row2 as $key=>$value) loop, use an accumulator to calculate "Column I". E.G. $tot += $value * $row1[$key]
"echo" the accumulater column before the </tr>
You also probably want to add an empty <td> in the $row1 loop to make sure that all the rows have the same number of columns.
You can traverse second table and calculate total with nested loop:
$res1 = mysql_query("SELECT * FROM `table1`");
$res2 = mysql_query("SELECT * FROM `table2`");
$row1 = mysql_fetch_row($res1);
$row = 0;
// for each row of second table
while ($row2 = mysql_fetch_row($res2)) {
$row++;
$total = 0;
// for each column of first table's row
foreach ($row1 as $index => $table1RowValue) {
// get value of same column in the second table's row
$table2RowValue = $row2[$index];
// calculate aggregated value
$total += $table1RowValue * $table2RowValue;
}
// print result
echo "Line $row: $total</br>";
}

How to echo a dynamic html snippet based on a MySQL databse with PHP?

I'm trying to create an image gallery with a for loop iterated by a counter of database rows.
To make it more clear: for each row in the table, get only the id(primary index) number and the image link from the server (not all the info in the row). With that information, echo an HTML image tag with the link inside the 'src=' and the id inside the 'alt='.
Two problems here:
1- the id number of the first row isn't zero.
2- I don't have a clue on how to get the total number of rows and to fetch only those two informations (id and img source).
That way, I could subtract the total number of rows minus the id number of the first row and using it to put an end on the loop.
So how to echo this dynamic html snippet based on my databse with PHP?
My code:
<?php
$link = mysqli_connect('localhost','user','pass','db');
$result = mysqli_query($link, "SELECT * FROM `table`");
$rows = mysqli_num_rows($result);
/* free result set */
mysqli_free_result($result);
$caption = mysqli_query($link, "SELECT ");
for($i=0; $i < $rows; $i++) {
echo "<img src='$imageURL' alt='$idNumber'>";
}
?>
You need to use sql functions to iterate through the dataset results. Replace your for loop... replacing 'image_url_column' and 'id_number_column' with the name of your actual columns in your db:
while ($row = while ($row = mysqli_fetch_assoc($caption)){){
echo "<img src='".$row['image_url_column']."' alt='".$row['id_number_column']."'>";
}
This is a really easy task.
First we fetch the data from the database using mysqli_query to do the query.
Then we use mysqli_fetch_array to get an array so then we can loop through it and echo each item.
After that, we mysqli_num_rows to get the total number of rows returned and increment it by 1 so it is not zero.
NOTE: Since you are going to increment the id to avoid getting a '0', don't to forget to minus '1' if you intend to use that id for some server-side purpose.
$result = mysqli_query($link, "SELECT * FROM `table`"); //query sql
$result_array=mysqli_fetch_array($result, MYSQLI_ASSOC);//return array from the query
$count = mysqli_num_rows($result); //get numbers of rows received
foreach($result as $row){ //do a foreach loop which is really simple
echo "<img src='". $row['img_column_name_from_db'] . "' alt='" .$row['id_column_name_from_db'] + 1 . "'>"; //echo data from the array, + 1 to "$row['id_column_name_from_db']" so that 'alt=' doesn't start from '0'.
}
echo $count;
You can use the count function of MySql to achieve the total number of rows.
also you can do this via mysqli_num_rows() function of mysql.
Code:
<?php
$link = mysqli_connect('localhost','user','pass','db');
$caption = mysqli_query($link, "SELECT id, img, count(id) as total from table");
echo
//$rows = mysqli_num_rows($result);
while($rows = mysqli_fetch_assoc($caption)){
echo "<img src='$rows[img]' alt='$rows[id]'>";
echo "Total Rows: ".$rows[total];
}
?>

PHP can't fetch last id inserted correctly

I have two possible solutions for my my probrem i want to echo last id inserted to know how many people fill the form, but it affects the data on the table below. Note: this doesn't affect the database itself, just the output from the browser.
connect.php
#$db = new mysqli('127.0.0.1', 'blop', 'blop', 'blop');
if ($db->connect_errno) {
die ('Sorry, we are having some problems.');
}
displaying the results:
function returnData() {
global $db;
echo ('<style> td {border: 1px solid #000; background:#ed8043;} th {border:1px solid #000; background:#fff</style>
<table style="width:100%; text-align:center;">
<tr>
<th>Line</th>
<th>id</th>
<th>Name</th>
<th>Email</th>
<th>Visited</th>
</tr>');
$result = $db->query("SELECT * FROM `people` ORDER BY `created` DESC");
$count = $result->num_rows;
echo 'Number of visits: ' .$count.'<br><br>';
/*$visits1 = $result->fetch_assoc();
echo $visits1['id']. '<br>';
$visits2 = $db->insert_id;
echo $visits2. '<br>';*/
$row_num = 1;
while ($row = $result->fetch_object()) {
echo ('
<tr>
<td>' .$row_num. '</td>
<td>' .$row->id. '</td>
<td>' .$row->first_name. '</td>
<td>' .$row->mail. '</td>
<td>' .$row->created.'</td>
</tr>'
);
$row_num++;
}
echo ('</table><br>');
$result->free();
}
The problem is that when i try like this: 1.
$result = $db->query("SELECT * FROM `people` ORDER BY `created` DESC");
$visits1 = $result->fetch_assoc();
echo $visits1['id']. '<br>';
i actualy have one more id than what appears on the table like the image below show:
As you can see i have "756" witch is fine, because it's the last id inserted but i don't want the respective row (with the id 756), it disapeared from the table below it. When i coment the code above it works fine the first row is the last id inserted.
I have an alternative code to resolve this, the problem is this doesn't work either: 2.
$result = $db->query("SELECT * FROM `people` ORDER BY `created` DESC");
$visits2 = $db->insert_id;
echo $visits2. '<br>';
This time the table it's correct, it shows all rows but the number of total id's it's 0.
That's what fetch_* methods are doing, and that's what you need so you can iterate over them. It's simple logic of programming loops. To execute a function n times, you put it in a loop, or call it manually n times. You call it manually one time, so you have already fetched the first item from this resultset. Putting it in a while() loop will fetch the remaining elements from the resultset.
To avoid this, you'd better switch to already fetched resultset and manipulate over it.
Right now, you are breaking the single responsibility principle, because returnData gets data, makes HTML and so on.
Make a function getData() with the query, and then use it with foreach to get all the resultset.
Use it only once to get the last Id (first).
function getData() {
global $db;
$result = $db->query("SELECT .......");
while ($row = $result->fetch_object()) {
$rows[] = $row;
}
return $rows;
}
Now in returnData() you can use
getData()[0]->id
To fetch the last id, as you can also iterate through the method without losing the resultset:
foreach (getData() as $data) {
echo $data->id;
}
You'd better make function for each thing you will need in this application. Fetching the last id, fetching the whole resultset, getting the rowcount, etc. It's rarely good practice to make it from a single query/method.
To be honest, there are a lot of issues to be fixed in your code, starting from global variables, ending to dropping the functional/procedural style in favor of OOP
Try to use:
SELECT `AUTO_INCREMENT`
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'blop'
AND TABLE_NAME = 'people';
In the first example, you should not do the second 'fetch_...' straight away. That's because you're discarding the first row, you've already fetched.
A quick (untested, sorry for typos) fix below:
...
$row = $result->fetch_object();
echo $row->id. '<br>';
$row_num = 1;
while ($row_num == 1 || $row = $result->fetch_object()) {
echo ('
<tr>
<td>' .$row_num. '</td>
<td>' .$row->id. '</td>
<td>' .$row->first_name. '</td>
<td>' .$row->mail. '</td>
<td>' .$row->created.'</td>
</tr>'
);
$row_num++;
}
...
From php documentation:
The mysqli_insert_id() function returns the ID generated by a query on a table with a column having the AUTO_INCREMENT attribute. If the last query wasn't an INSERT or UPDATE statement or if the modified table does not have a column with the AUTO_INCREMENT attribute, this function will return zero.
So SELECT queries do not return the last inserted id.
In general this query should work for the last row of a table ordered by a column:
select column_name from table_name order by column_name desc limit 1;
For id you can also use:
select LAST_INSERT_ID() from table;
which doesn't force you to make an INSERT or UPDATE query before this query.

2 while loops in php - mysql select statement

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

How To Create Mysql Select Statement With Limit

Hello. I need help with doing a mysql select, where the values in wins is higher than lets say 100 ? So it selects only the users who have had more than 100 win's
Then i need to inserts each one into a table.
Here is what i have so far
<?php
// i have toke my connect out
// Get all the data from the "example" table
$result = mysql_query("SELECT * FROM users")
or die(mysql_error());
echo "<table border='1'>";
echo "<tr> <th>username</th> <th>wins</th> </tr>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo "<tr><td>";
echo $row['username'];
echo "</td><td>";
echo $row['wins'];
echo "</td></tr>";
}
echo "</table>";
?>
I am guessing id need a were statement ? Saying select were wins > 100 ? I have done loads of select were's be for but never select were is over. I also will need to insert each one of the results into another table called rewards
Your current query SELECT * FROM users will give you ALL data that is present in your table.
To get the data where wins > = 100 just add this condition so that new statement will be
SELECT * FROM users where wins >= 100
To insert into rewards table (considering you have fields as username, wins) use below
insert into rewards
(username, wins)
select username, wins
from users
WHERE wins >= 100

Categories