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>";
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.
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.
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 am running a fairly straight forward mysql request and returning the results to a table. There were three record in the db, and the query is pulling from two tables. As a result, I am getting a count of three records (echoing mysql_num_rows), but only two show in the table. Using a print_r command on the array result shows only one particular record - the other records do show in the print-r.. I added another record to the db, and now three records show - and the same record as before does not show and is the only record in the print_r command.
Here's the relevant code:
<td id="page1">
<?php
$limit = 15; // Set limit to show for pagination
$page = $_GET['page']; // get page number from submit
if($page)
$start = ($page - 1) * $limit; // first item to display on this page
else
$start = 0; // if no page var is given, set start to 0
$query = "SELECT PartyMstr.PartyMstrID, UserName, FirstName, LastName, XrefPartyRoleID
FROM PartyMstrRole, PartyMstr
WHERE PartyMstr.PartyMstrID = PartyMstrRole.PartyMstrID &&
PartyMstrRole.XrefPartyRoleID = 1
ORDER BY LastName, FirstName ASC
LIMIT $start, $limit
";
$result = mysql_query($query, $connection);
$row = mysql_fetch_array($result) or die(mysql_error());
$totalitems1 = mysql_num_rows($result);
?>
<center><h3> Admin User List </h3></center>
<?php
echo "<table border=\"1\" align=\"center\">";
echo "<tr><th>PartyMaster ID</th>";
echo "<th>UserName</th>";
echo "<th>Last, First</th>";
echo "<th>Link</th></tr>";
while($row = mysql_fetch_array($result)) {
echo "<tr><td>";
echo $row['PartyMstrID'];
echo "<td>";
echo $row['UserName'];
echo "<td>";
echo " " . $row['LastName'] . ", " . $row['FirstName'] . " ";
echo "<td>";
echo "<a href = \"http://www.505575.com/editUser.php?id=" . $row['PartyMstrID'] . "\" >Edit</a>";
// echo "<td>";
// echo $row['XrefPartyRoleID'];
echo "</td></tr>";
}
echo "</table><br/><br/> ";
$paginaton = getPaginationString( $page, $totalitems, $limit,
$adjacents = 1,
$targetpage = "adminUserList.php",
$pagestring = "?page="
); // Functon found in functions.php
echo $paginaton;
?>
</td>
I've spent a lot of time online looking for an explanation without success. I've switched off the $pagination code line without effect. I have tried various other tricks and echoed output. The number of rows returned (n) is always correct, but only n-1 rows appear in the table. Any ideas out there?
Thanks - Don
Every time you call mysql_fetch_array you are taking a row from the resource. When the resource has no more rows to give, it returns false. That's how while ($a = mysql_fetch_array($resource)) loops work.
$result = mysql_query($query, $connection);
$row = mysql_fetch_array($result) or die(mysql_error());
$totalitems1 = mysql_num_rows($result);
// first row is taken from resource
....
while($row = mysql_fetch_array($result))
// now take the rest of the rows
As you can see, your code is doing exactly what you tell it to! Just remove the first $row = mysql_fetch_array($result) or die(mysql_error()); as it doesn't serve any purpose anyway.
You are fetching the first result outside your while loop.
$query = "SELECT PartyMstr.PartyMstrID, UserName, FirstName, LastName, XrefPartyRoleID
FROM PartyMstrRole, PartyMstr
WHERE PartyMstr.PartyMstrID = PartyMstrRole.PartyMstrID && PartyMstrRole.XrefPartyRoleID = 1
ORDER BY LastName, FirstName ASC
LIMIT $start,$limit";
$result = mysql_query($query, $connection);
$row = mysql_fetch_array($result) or die(mysql_error());
$totalitems1 = mysql_num_rows($result);
needs to be:
$query = "SELECT PartyMstr.PartyMstrID, UserName, FirstName, LastName, XrefPartyRoleID
FROM PartyMstrRole, PartyMstr
WHERE PartyMstr.PartyMstrID = PartyMstrRole.PartyMstrID && PartyMstrRole.XrefPartyRoleID = 1
ORDER BY LastName, FirstName ASC
LIMIT $start,$limit";
$result = mysql_query($query, $connection);
$totalitems1 = mysql_num_rows($result);
As the others intimate, the problem is that you're calling mysql_fetch_array() once, on the line after $result = mysql_query( ..., before you go into your while loop. This takes the first row from your results, but you never do anything with it. Then when you start your while loop you call mysql_fetch_array() again, but since you've already taken the first row, it starts with the second row.
okay you must understand why it ignore 1 row lets see $row = mysql_fetch_array($result) or die(mysql_error()); this code fetch your 1st row already and then you fetch in loop so it pointed row after the row is already fetched.
$limit = 15; // Set limit to show for pagination
$page = $_GET['page']; // get page number from submit
if($page)
$start = ($page - 1) * $limit; // first item to display on this page
else
$start = 0; // if no page var is given, set start to 0
$query = "SELECT PartyMstr.PartyMstrID, UserName, FirstName, LastName, XrefPartyRoleID
FROM PartyMstrRole, PartyMstr
WHERE PartyMstr.PartyMstrID = PartyMstrRole.PartyMstrID &&
PartyMstrRole.XrefPartyRoleID = 1
ORDER BY LastName, FirstName ASC
LIMIT $start, $limit
";
$result = mysql_query($query, $connection);
$row = mysql_fetch_array($result) or die(mysql_error());
$totalitems1 = mysql_num_rows($result);
?>
<center><h3> Admin User List </h3></center>
<?php
echo "<table border=\"1\" align=\"center\">";
echo "<tr><th>PartyMaster ID</th>";
echo "<th>UserName</th>";
echo "<th>Last, First</th>";
echo "<th>Link</th></tr>";
while($row = mysql_fetch_array($result)) {
echo "<tr><td>";
echo $row['PartyMstrID'];
echo "<td>";
echo $row['UserName'];
echo "<td>";
echo " " . $row['LastName'] . ", " . $row['FirstName'] . " ";
echo "<td>";
echo "<a href = \"http://www.505575.com/editUser.php?id=" . $row['PartyMstrID'] . "\" >Edit</a>";
// echo "<td>";
// echo $row['XrefPartyRoleID'];
echo "</td></tr>";
}
echo "</table><br/><br/> ";
$paginaton = getPaginationString( $page, $totalitems, $limit,
$adjacents = 1,
$targetpage = "adminUserList.php",
$pagestring = "?page="
); // Functon found in functions.php
echo $paginaton;
?>
</td>
I have my data stored in a MySQL table, which includes an auto_increment ID number (unique) for each new row.
I'd like users to be able to get a certain ID number, using the $_GET function.
eg. User loads http://mysite.com/id.php?id=123
Page displays ID number 123 along with the row.
echo $row['id'];
echo "<table>";
echo "<tr> <th>Unit</th> <th>Message</th> <th>Date</th> </tr>";
while($row = mysql_fetch_array( $result )) {
echo "<tr><td>";
echo $row['title'];
echo "</td><td>";
echo $row['description'];
echo "</td><td>";
echo $row['pubDate'];
echo "</td></tr>";
}
echo "</table>";
echo "</center>";
I'm stuck as to where I put the $_GET bit.
Thanks :)
You should append it to your query (using intval to avoid SQL injection) like this:
// use the id in your WHERE clause, convert it to an integer to avoid sql injections
$query = 'SELECT fields FROM table WHERE id = ' . intval($_GET['id']);
$result = mysql_query($query);
$row = mysql_fetch_row($result);
... do stuff with $row ...
Firstly, your code does not make much sense, since you use $row before it was defined.
Secondly, $result isn't defined at all, and it should be, for example like this:
$id = intval($_GET['id']);
$result = mysql_query("SELECT FROM table WHERE id = '$id'");
And now you know how and where to use $_GET['id'].
Dont waste your time doing the comparison afterwards, you'll save yourself alot of time by adding it to the original query
$id = intval($_GET['id']);
$query = "SELECT whatever FROM table WHERE id=$id";
$id = $_GET['id'];
$id = mysql_real_escape_string($id);
$query = "SELECT * FROM `Table` WHERE `id`='" . $id . "'";
$res = mysql_query ($query);
$exist = mysql_num_rows($res);
if ($exist) {
$row = mysqlfetch_assoc($res);
...
}