I did loop of input tags in a form. My code for this one is:
$sql = "SELECT * FROM inventory_tbl";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
echo "<table>
<tr>
<th>Product SKU</th>
<th>Category</th>
<th>Product Name</th>
<th>Size</th>
<th>Quantity</th>
</tr>";
if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr>
<td>" . $row['product_sku'] . "<input type='hidden' name='productsku[]' value='" . $row['product_sku'] . "'></td>
<td>" . $row['product_category'] . "</td>
<td>" . $row['product_name'] . "</td>
<td>" . $row['product_size'] . "</td>
<td><input type='text' name='productqty[]'></td>
</tr>";
}
}
And this is code when I'm putting the data to database:
$event_name = $_POST['eventname'];
$event_date = $_POST['eventdate'];
$event_place = $_POST['eventplace'];
$amount = $_POST['amount'];
$product_sku = $_POST['productsku'];
$quantity = $_POST['productqty'];
$sqlcount_product = "SELECT COUNT(product_sku) FROM inventory_tbl WHERE is_deleted = 0;";
$result = mysqli_query($conn, $sqlcount_product);
$y = mysqli_fetch_assoc($result);
$sqlst = "INSERT INTO stalltransaction_tbl(event_name, event_place, event_date) VALUE ('$event_name', '$event_place', '$event_date');";
if (mysqli_query($conn, $sqlst)) {
$last_id = mysqli_insert_id($conn);
}
$x = 0;
while ($x<$y) {
if (!empty($quantity[$x])) {
$sqlo = "INSERT INTO stallitems_tbl(stransaction_no, item_no, product_sku, quantity) VALUE ('$last_id', '$x+1', '$product_sku[$x]', '$quantity[$x]');";
mysqli_query($conn, $sqlo);
$sqlr = "UPDATE inventory_tbl
SET no_of_stock = (no_of_stock - '$quantity[$x]'), no_of_avstock = (no_of_avstock - '$quantity[$x]')
WHERE product_sku = '$product_sku[$x]';";
mysqli_query($conn, $sqlr);
}
$x=$x+1;
}
$x=0;
$sqla = "UPDATE stransaction_tbl
SET total_amount = (SELECT SUM(I.item_price*O.quantity) FROM order_tbl O JOIN inventory_tbl I ON O.product_sku = I.product_sku WHERE O.transaction_no = '$last_id')
WHERE transaction_no = '$last_id';";
mysqli_query($conn, $sqla);
$sqlp = "INSERT INTO payment_tbl(transaction_no, payors_name, payment_mode, payment_date, amount) VALUE ('$last_id', '$event_name', 'Cash', '$event_date', '$amount');";
mysqli_query($conn, $sqlp);
header("Location: ../index.php?newstransaction=success");
The inputting to database works in stallitems_tbl insert loop. It does the code above but after that loop it stops. I know because the database stransaction and payment hasn't changed. It says like 'Maximum execution time of 30 seconds exceeded'. Help me. Is my code correct? Thanksss
I really don't want to do a complete code review on this question, but I have a sneaking suspicion that it is over-complicated.
As for your:
Maximum execution time of 30 seconds exceeded
I reckon you have an infinite loop because $x is never stopped by the associative resultset row.
I recommend:
$y = mysqli_fetch_row($result)[0];
...this should be a number.
p.s. I'll remove my comments and include my other recommendations:
You should be implementing mysqli prepared statements with placeholders for security reasons.
A for ($x=0; $x<$y; ++$x) { loop will be a much cleaner syntax than $x=0; while($x<$y){...$x=$x+1;}.
And finally, your script is performing no affected row checking, so header(...success) is a bit of an assumption. UPDATE queries can be error-free and still affect zero rows, so you would be wise to include some checkpoints along the way.
your while check in the main loop will never exit.
$y = mysqli_fetch_assoc($result); will contain an array
$x = 0;
while ($x<$y) {
}
$x is an integer, so comparing the 2 will resolve to true. Hence your loop wont ever exit.
edit
As mentioned in comments, your result set will contain a count, but will be accessible in an array. So you need to extract it before you can use it as you are trying to.
However, take note of all the comments. The code is messy and not well thought out. Simple housekeeping such as good indenting will help you debug more effectively.
In addition, if you use a good IDE then most of those housekeeping jobs become automatic. Also consider using xdebug, being able to step through the code line by line is an essential tool.
Related
I am trying to form a string for the picture info in a lightbox gallery display. Originally I just used the following
<td><div style='height:175px;'></div></td><td><a href='images/memwork/".$cell1['folder']."/".$cell1['filename']."' data-lightbox='image-".$cell1['id']."' data-title='".$cell1['title']." by ".$cell1['artist']."<br />".$cell1['medium']." ".$cell1['width']." x ".$cell1['height']." cm. <br />Price: £".$cell1['priceu']."'><img class='tn' src='images/memwork/".$cell1['folder']."/".$cell1['tn']."' /></a></td>
But this became a nightmare trying to trap zero prices, dimensions or medai types with ternary operators so I am now trying to format the data with IF statements and add the result into the data array. However, I seem to have missed something as the result is always just " by ". My code is:
$query = "SELECT * FROM gallery WHERE sig=1 LIMIT $start,6";
}
$result = mysqli_query($db, $query);
$i=1;
while($row = mysqli_fetch_assoc($result)) {
${'cell'.$i} = $row;
$gal_artist = $row['artist'];
$query = "SELECT COUNT(*) AS num FROM gallery WHERE artist='$gal_artist'";
$total = mysqli_fetch_array(mysqli_query($db,$query));
${'cell'.$i}['num_pics'] = $total['num'];
$picdata = ${'cell'.Si}['title']." by ".${'cell'.Si}['artist'];
if (${'cell'.Si}['medium'].${'cell'.Si}['width'] !='') $picdata = $picdata."<br />";
if (${'cell'.Si}['width'] >0) $picdata = $picdata." ".${'cell'.Si}['medium']." ".${'cell'.Si}['width']." x ".${'cell'.Si}['height']." cm.";
if (${'cell'.Si}['price'] >0) $picdata = $picdata."<br />Price: £".${'cell'.Si}['price'];
${'cell'.Si}['picdata'] = $picdata;
$i++;
}
and the table data statements should simplify to
<td><div style='height:175px;'></div></td><td><a href='images/memwork/".$cell1['folder']."/".$cell1['filename']."' data-lightbox='image-".$cell1['id']."' data-title='".$cell1['picdata']."'><img class='tn' src='images/memwork/".$cell1['folder']."/".$cell1['tn']."' /></a></td>
You're using Si instead of $i in your code. In addition, I would suggest you to use array instead of dynamic variable name, which is usually a bad practice.
So :
$result = mysqli_query($db, $query);
$i=1;
while($row = mysqli_fetch_assoc($result)) {
$cells[$i] = $row;
$gal_artist = $row['artist'];
$query = "SELECT COUNT(*) AS num FROM gallery WHERE artist='$gal_artist'";
$total = mysqli_fetch_array(mysqli_query($db,$query));
$cells[$i]['num_pics'] = $total['num'];
$picdata = $cells[$i]['title']." by ".$cells[$i]['artist'];
if ($cells[$i]['medium'].$cells[$i]['width'] !='') $picdata = $picdata."<br />";
if ($cells[$i]['width'] >0) $picdata = $picdata." ".$cells[$i]['medium']." ".$cells[$i]['width']." x ".$cells[$i]['height']." cm.";
if ($cells[$i]['price'] >0) $picdata = $picdata."<br />Price: £".$cells[$i]['price'];
$cells[$i]['picdata'] = $picdata;
$i++;
}
Then print it like
<td><div style='height:175px;'></div></td><td><a href='images/memwork/".$cells[1]['folder']."/".$cells[1]['filename']."' data-lightbox='image-".$cells[1]['id']."' data-title='".$cells[1]['picdata']."'><img class='tn' src='images/memwork/".$cells[1]['folder']."/".$cells[1]['tn']."' /></a></td>
First thing you need to update your sql query by using below query.
SELECT t.*, (Select count(*) from test AS t1 where t.artist= t1.artist) AS album_count
FROM test AS t
I hope this will be helpful for you.
It calculates, but starting from the second row.
<?php
include('connect-db.php');
$query = "select * from users";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
$sold= array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$sold=$row['contract']+$row['tva'];
echo "<table><tr><td>" . $sold. "</td></tr></table>";
}
?>
Your code has many issues:
Your code starts to calculate from the second row because of the line:
$row = mysql_fetch_array($result);
which obtains the first result from the opened recordset before the while loop.
$sold = array();Why is that an array?
If you want to sum to $sold, threat the variable as an integer and initialize it with a 0.
$sold = 0;
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
$sold += $row['contract']+$row['tva'];
echo "<table><tr><td>" . $sold. "</td></tr></table>";
It seems to me also that you may want to print the table only once. If this is true, consider to query the database with an aggregation function like SUM():
SELECT SUM(contract + iva) AS contractIva FROM users GROUP BY <some column in your table>;
The above allows to remove the while loop.
Since you already extracted a row from the result, with $row = mysql_fetch_array($result);, the script starts adding only with the next row. Th correct code would be:
<?php
include('connect-db.php');
$query = "select * from users";
$result = mysql_query($query);
$sold= array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$sold=$row['contract']+$row['tva'];
echo "<table><tr>
<td>" . $sold. "</td>
</tr></table>";
}
?>
you can do that via query as well so that you don't need to perform calculation on the application level, database level can do this job for you.
select sum(col1+col2) as total from users
And you want one table instead of multiple tables I guess, if yes then do it like this:
echo "<table>
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$sold=$row['contract']+$row['tva'];
echo <tr><td>" . $sold. "</td></tr>";
}
echo "</table>";
I have a problem with getting the right value after I counted the rows from a table. I searched on the web but didn't find an answer.
In the database i have a table with all the categories in it they all have an id, and i would like to count using this column.
I have this PHP code, it works but is there an other and better to get over this?
$sql2 = "SELECT COUNT(id) FROM categories";
$stmt2 = sqlsrv_query($conn, $sql2);
$res = sqlsrv_fetch_array($stmt2, SQLSRV_FETCH_ASSOC);
foreach($res as $row)
{
$rows = $row;
}
//if there are categories display them otherwise don't
if ($rows > 0)
{
$sql = "SELECT * FROM categories";
$stmt = sqlsrv_query($conn, $sql);
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
echo "<a href='#' class='cat_links'>" . $row['category_name'] . " - <font size='-1'>" . $row['category_description'] . "</font></a>";
}
}
else
{
echo "<p style='text-align: center'>No categories yet.</p>";
}
I think has to be a better way to convert the $stmt2 variable from a SQL resource to an actual number, or to convert the $res variable from an array to an number. If I try to echo the whole array using foreach, it will only print out the number of rows. This is why I use it to count the rows now.
I can't use the sqlsrv_num_rows function because I then get an error, or no answer.
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("students");
$id = $_POST['id'];
$grade = $_POST['grade'];
$query = "INSERT INTO `st_table` (`St_id`,`Grade`) VALUES ('$id','$grade')";
$result = mysql_query($query);
$query = "SELECT * from `st_table`";
$result = mysql_query($query);
echo "<table>";
echo "<th>St_id</th><th>Grade</th>";
while($row = mysql_fetch_array($result)){
echo "<tr><td>" . $row['St_id'] . "</td><td>" . $row['Grade'] . "</td></tr>";
}
This code adds values into a table both ID and Grade. I want another query that will be able to count how many As, Bs, Cs, etc. and OUTPUT it on an html table.
Here, Your query is ok just group by Grade not Grades
"SELECT `Grade`, COUNT(*) AS count FROM `st_table` GROUP BY `Grade`";
Here is sqlfiddle
After edit
The query i am mentioning should work for you, you can check fiddle for that as for as you modified code is concerned you have to change your table a bit since you are going to include St_id as well so make it 3 column and correspondingly change query too.
I am not sure how to do this. From the answer I've found on here, I think it's possible using jquery/ajax maybe. I need to get the value of my variable $i and echo it at the top, but it has to go through my logic to get to the value. Here is my code:
echo "<div id='records'><h1 align='center'>Today's Transfers (" . $i . ") </h1>
<table cellspacing='0' cellpadding='0'>
<tr>
<th>Customer Name</th><th>Phone Number</th><th>Disposition</th><th>User</th><th>Date Called</th>
</tr>
";
$i=0;
$sql = "SELECT * FROM vicidial_closer_log WHERE DATE(call_date) = DATE(NOW()) ORDER BY call_date DESC";
$result = mysqli_query($link, $sql, MYSQLI_STORE_RESULT);
while($row = $result->fetch_assoc()){
$i++;
$phone_number = $row['phone_number'];
$lead_id = $row['lead_id'];
$disposition = $row['status'];
...then echo those variable in my columns and rows...
}
echo "</table> </div>";
echo $i;
Maybe there is another way to write my code so the logic comes before I output everything? Not sure how to do that though since I'm using a mysql query.
You should get the number of rows from the result set and display those where the i is, since it is essentially the same thing.
$num_rows = mysql_num_rows($result);
Move your code above the echo statement:
$i=0;
$sql = "SELECT * FROM vicidial_closer_log WHERE DATE(call_date) = DATE(NOW()) ORDER BY call_date DESC";
$result = mysqli_query($link, $sql, MYSQLI_STORE_RESULT);
and add
$num_rows = mysql_num_rows($result);
echo "<div id='records'><h1 align='center'>Today's Transfers (" . $num_rows . ") </h1>
and use the rest of your code as before .. Might think about removing i if you don't need it for something else.
If $i is the total number of returned results, you could do:
echo mysqli_num_rows($result)
... and have your query executed at the top of the page.
This would ideally be all in a model and being set in a view by a controller however. That way you're separating the presentation from the functional logic.
I suggest you have a read about MVC:
Sure, you can just move the echo above your logic. But the best to do is to separate logic from presentation. You can create a class to handle this or maybe just another file, it depends on your needs.
$i=0;
$sql = "SELECT * FROM vicidial_closer_log WHERE DATE(call_date) = DATE(NOW()) ORDER BY call_date DESC";
$result = mysqli_query($link, $sql, MYSQLI_STORE_RESULT);
while($row = $result->fetch_assoc()){
$i++;
$phone_number = $row['phone_number'];
$lead_id = $row['lead_id'];
$disposition = $row['status'];
echo "<div id='records'><h1 align='center'>Today's Transfers (" . $i . ") </h1>
<table cellspacing='0' cellpadding='0'>
<tr>
<th>Customer Name</th><th>Phone Number</th><th>Disposition</th><th>User</th><th>Date Called</th>
</tr>";
Do your computations first, then display your data.
Horribly mangled example code:
$count = 0;
$output = '';
$res = mysqli_query("SELECT * FROM...");
while( $row = mysql_fetch($res) ) {
$output .= "<tr><td>..." . $row['somevar'] . "</td></tr>";
$count++;
}
echo "<h1>Yadda yadda $count</h1>";
echo "<table>";
echo $output
echo "</table>";