PHP / mySQL - for loop doesn't work properly - php

I have these lines of code:
$user = $_SESSION['name'];
$con = mysqli_connect("localhost","root","","db_shop");
$sql = mysqli_query($con,"SELECT * FROM tbl_cart WHERE `user` = '$user' AND `done` = '0'");
while( $result = mysqli_fetch_assoc( $sql ) ){
$file = $result['items'];
$res = explode(",",$file);
$total = 0;
$tmp = count( $res );
for( $i = 0 ; $i <= $tmp; $i++ ){
$sql = "SELECT * FROM `tbl_details` WHERE `file_name` = '".$res[$i]."'";
echo $sql;
$sql = mysqli_query( $con, "SELECT * FROM `tbl_details` WHERE `file_name` = '".$res[$i]."'");
while( $res = mysqli_fetch_assoc( $sql ) ){
$total += $res['price'];
}
echo "<script>alert('$total');</script>";
}
}
where $res[1] must contain a value of 1000 from my database, but it just gives me a null value.
As you can see I tried to echo out $sql, $res[0] returned the right one but $res[1] returned:
SELECT * FROM `tbl_details` WHERE `file_name` = ''
Any help would be appreciated thanks.

I wonder whether it is because the inner sql statement references the same variable name $sql? Changed the inner variable names ....
$user = $_SESSION['name'];
$con = mysqli_connect("localhost","root","","db_shop");
$sql = mysqli_query($con,"SELECT * FROM tbl_cart WHERE `user` = '$user' AND `done` = '0'");
while( $result = mysqli_fetch_assoc( $sql ) ){
$file = $result['items'];
$res = explode(",",$file);
$total = 0;
$tmp = count( $res );
for( $i = 0 ; $i < $tmp; $i++ ){
$sql_inner = "SELECT * FROM `tbl_details` WHERE `file_name` = '".$res[$i]."'";
#echo $sql_inner;
$res_inner = mysqli_query( $con, "SELECT * FROM `tbl_details` WHERE `file_name` = '".$res[$i]."'");
while( $row = mysqli_fetch_object( $res_inner ) ){
$total += $row->price;
}
echo "<script>alert('$total');</script>";
}
}

You should change $i <= $tmp to $i < $tmp.
Because count $tmp = count( $res ); returns number of elements but not the max index of element.
for( $i = 0 ; $i < $tmp; $i++ ){
and here you should use another variable name not $res:
while( $row = mysqli_fetch_assoc( $sql ) ){
$total += $row['price'];
}

Related

How to add values to in the result of while loop in php

How to add the result of the while loop which is stored on the variable $profit? results are 5 and 70
the code
<?php
$sql2 = "SELECT * from `products`";
$result2 = $link->query($sql2);
while($row2 = $result2->fetch_assoc())
{
$sql3 = "SELECT * from `orders` where product_id = '".$row2['prod_id']."'";
$result3 = $link->query($sql3);
$row3 = $result3->fetch_assoc();
$sql = "SELECT SUM(product_qty) from orders where product_id = '".$row2['prod_id']."'";
$result = $link->query($sql);
$row = mysqli_fetch_array($result);
$res = bcmul($row2['prod_price'], $row[0]);
$profit = $res - $row2['prod_cost'];
if($row[0] == null){
$row[0] = 0;
}
}?>
Try this code
<?php
$sql2 = "SELECT * from `products`";
$result2 = $link->query($sql2);
$totalProfit = 0;
while($row2 = $result2->fetch_assoc())
{
$sql3 = "SELECT * from `orders` where product_id = '".$row2['prod_id']."'";
$result3 = $link->query($sql3);
$row3 = $result3->fetch_assoc();
$sql = "SELECT SUM(product_qty) from orders where product_id = '".$row2['prod_id']."'";
$result = $link->query($sql);
$row = mysqli_fetch_array($result);
$res = bcmul($row2['prod_price'], $row[0]);
$profit = $res - $row2['prod_cost'];
$totalProfit = $totalProfit + $profit
if($row[0] == null){
$row[0] = 0;
}
}?>
now you can use $totalProfit variable value as total.

How can I make this code short and easy to read?

I have more than 10 lines like this and I want to echo just 5 rows per page this is my code.
$c = mysqli_fetch_field_direct;
$c1 = $c($result,2)->name;
$c2 = $c($result,3)->name;
$c3 = $c($result,4)->name;
//$cn,...;
echo "$row[2]" ; echo "$c1[2]";
echo "$row[3]" ; echo "$c1[3]";
//echo "$row[n]" , ...;
Before this code I have this:
$sql = "SELECT * FROM sheet1 WHERE id = '$_POST[text]'";
$result = mysqli_query($con,$sql);
If ($row = mysqli_fetch_array($result))
{
//the 10 lines of codes above
}
You may want to loop through these elements:
$sql = "SELECT * FROM sheet1 WHERE id = '$_POST[text]'";
$result = mysqli_query($con,$sql);
If ($row = mysqli_fetch_array($result))
{
for($i = 2; $i < 10; $i++){
$c = mysqli_fetch_field_direct($result,$i)->name;
echo $row[$i] ; echo $c[$i];
}
}

Display Last userID in php from MySQL

I am trying to echo last userID stored in MySQL. But it is not shown. No error is displayed.
I tried:
$stmti = $reg_user->runQuery("SELECT * FROM tbl_users");
$rowi = $stmti->fetch(PDO::FETCH_ASSOC);
$tf = $rowi['userID'];
echo $tf;
/* NOTE: This works only with mysqli
change the parameters "host","username","password","db_name" with your
own ones
*/
$link = mysqli_connect("host","username","password","db_name");
$query = " SELECT *
FROM tbl_users";
$rows = array();
$result = mysqli_query($link, $query);
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC))
$rows[] = $row;
$lastID = 0;
for ($i = 0 ; $i < count($rows) ; $i++)
$lastID = $i;
echo $rows[$lastID]["userID"];
try this :
$sth = $reg_user->prepare("SELECT MAX(userID) as userID FROM tbl_users");
$sth->execute();
$result = $sth->fetch(PDO::FETCH_ASSOC);
$tf= ($result['userID']);
echo $tf;

Table prints multiple column headers while filtering results

How can I stop my table from printing multiple column headers after I filter my results?? Example like shown below
My code
function fillQueryData() {
$dbName = $_REQUEST ['db'];
$link = mysqli_connect ( '192.168.2.113', 'root', '', $dbName );
if (! $link) {
die ( "Connection failed" . mysqli_errno ( $link ) );
}
if (isset ( $_POST ['name'] )) {
$name = trim ( $_POST ['name'] );
$tblName = $_REQUEST ['tbl'];
$colqry = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '$dbName' AND TABLE_NAME = '$tblName'";
$col_names = mysqli_query ( $link, $colqry );
while ( $col = mysqli_fetch_array ( $col_names, MYSQLI_ASSOC ) ) {
$colName = $col ['COLUMN_NAME'];
$tblQry = "SELECT * FROM $tblName WHERE $colName='$name' LIMIT 15";
$query2 = mysqli_query ( $link, $tblQry );
echo "<table><tr>";
$i = 0;
while ( $i < mysqli_num_fields ( $query2 ) ) {
$meta = mysqli_fetch_field_direct ( $query2, $i );
echo "<th>" . $meta->name . "</th>";
$i = $i + 1;
}
echo "</tr>";
$i = 0;
while ( $row = mysqli_fetch_row ( $query2 ) ) {
echo "<tr>";
$count = count ( $row );
$y = 0;
while ( $y < $count ) {
$c_row = current ( $row );
echo "<td>" . $c_row . "</td>";
next ( $row );
$y = $y + 1;
}
echo "</tr>";
$i = $i + 1;
}
echo "</table>";
} }
}
I didn't want to put the table data while loops inside my column name while loop but if I don't I wont get any results in the rows. How can I work around this issue so only the filtered results are displayed??
Column header loop should be outside the data-fetch loops
Code should be like this.
function filterTblData() {
$dbName = $_REQUEST ['db'];
$link = mysqli_connect ( '192.168.2.113', 'root', '', $dbName );
if (! $link) {
die ( "Connection failed" . mysqli_errno ( $link ) );
}
if (isset ( $_POST ['name'] )) {
$name = trim ( $_POST ['name'] );
$tblName = $_REQUEST ['tbl'];
// Dynamically select the column names of the chosen table.
$colqry = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '$dbName' AND TABLE_NAME = '$tblName'";
$col_names = mysqli_query ( $link, $colqry );
$col = mysqli_fetch_array ( $col_names, MYSQLI_ASSOC );
$colName = $col ['COLUMN_NAME'];
// Selecting and filtering results based on matching search terms.
$tblQry = "SELECT * FROM $tblName WHERE $colName='$name' LIMIT 15";
$query2 = mysqli_query ( $link, $tblQry );
echo "<table><tr>";
// Loop for fetching table column headers and riprinting them.
$i = 0;
while ( $i < mysqli_num_fields ( $query2 ) ) {
$meta = mysqli_fetch_field_direct ( $query2, $i );
echo "<th>" . $meta->name . "</th>";
$i = $i + 1;
}
echo "</tr>";
// Fetch row data and populate
while ( $col = mysqli_fetch_array ( $col_names, MYSQLI_ASSOC ) ) {
$colName = $col ['COLUMN_NAME'];
// Selecting and filtering results based on matching search terms.
$tblQry = "SELECT * FROM $tblName WHERE $colName='$name' LIMIT 15";
$query2 = mysqli_query ( $link, $tblQry );
$i = 0;
while ( $row = mysqli_fetch_row ( $query2 ) ) {
echo "<tr>";
$count = count ( $row );
$y = 0;
while ( $y < $count ) {
$c_row = current ( $row );
echo "<td>" . $c_row . "</td>";
next ( $row );
$y = $y + 1;
}
echo "</tr>";
$i = $i + 1;
}
}
echo "</table>";
}
}
filterTblData();

Update statement in MYSQL from PHP

I have a table as shown below
The output from said table
Green, is where a winner has been announced, whereas yellow means they have submitted a report, but a winner hasn't been decided yet. (winner field not populated)
$roundBound = Array();
$query = "SELECT MIN(id), MAX(id) FROM $tablename GROUP BY round";
if($result = $Login->mysqli->query($query)) {
while ($row = $result->fetch_row()) {
$roundBound[] = $row[0];
$roundBound[] = $row[1];
}
}
for($i = 0; $i < count($roundBound); $i = $i + 2) {
$match = 0;
for($j = $roundBound[$i]; $j < $roundBound[$i + 1]; $j = $j + 2) {
$id1 = $j;
$id2 = $j+1;
$query = "SELECT t1.winner, t2.winner FROM $tablename as t1, $tablename as t2 WHERE t1.id=$id1 AND t2.id=$id2";
$result = $Login->mysqli->query($query);
$row = $result->fetch_row();
$win1 = $row[0];
$win2 = $row[1];
if (isset($win1) && isset($win2)) {
if (isset($roundBound[$i + 2])) {
$id = $roundBound[$i + 2] + $match;
$query = "UPDATE $tablename SET
username = '$win1',
username2 = '$win2'
WHERE id = $id";
$Login->mysqli->query($query);
} else {
//Tourneydonneee yeeee
}
}
$match++;
}
}
Does anyone have a improvement, or an all-around different idea? This will be running quite often and could be potentially running on large record sets, so optimization would also be welcome.
as far as i understand you problem, i can suggest you to try
for ($i = 0; $i < count($arr); $i = $i + 2) {
$win1 = mysql_query("SELECT winner FROM tableName WHERE id=".(int)$i);
$win2 = mysql_query("SELECT winner FROM tableName WHERE id=".(int)$i+1);
$qry = "INSERT INTO tableName SET
username = $win1,
username2 =$win2,
....";
mysql_query($qry);
}

Categories