php explode product array throwing up errors - php

I have set up an 'orders' page that should be pretty straight-forward, requiring a for each loop to generate past orders from the DB. Within each loop, there needs to be an explode to separate each item(,), then another explode to pull the details out of each item(-). I was wondering if anyone could tell me why I'm getting the error message "Warning: mysql_num_rows() expects parameter 1" at the end of each iteration of my foreach loop? It's particularly confusing for me because the code still works, which I don't think it should if the error was true.
<?php
$sql = "SELECT * FROM orders WHERE store='$user'";
$res = mysql_query($sql);
$arrOrders = array();
while ($row = mysql_fetch_array($res)) {
array_push($arrOrders, $row);
}
?>
<table width="85%" align="center" border="0" cellpadding="5">
<?php if (count($arrOrders) > 0) { ?>
<?php foreach ($arrOrders as $key => $value) { ?>
<tr>
<td valign="top" style="font-weight: bold">
ID #<?=$value['id']?>
</td>
<td valign="top" style="font-weight: bold">
Status: <?=$value['status']?>
</td>
<td valign="top" style="font-weight: bold">
Order #<?=$value['order_ref']?>
</td>
<td align="left" valign="top" style="font-weight: bold">
<?php
$tmpProds = explode(',', $value['products']);
foreach ($tmpProds as $key2 => $value2) {
$tmpProdInfo = explode('-', $value2);
$sql2 = 'SELECT * FROM products_full WHERE id = ' . $tmpProdInfo[0];
$res2 = mysql_query($sql2);
if (mysql_num_rows($res2) > 0) { // THIS IS THE ROW THAT THE ERROR MESSAGE POINTS TO
echo $tmpProdInfo[1] + $tmpProdInfo[2] . ' x ' . mysql_result($res2, 0, 'alpha_code') . ' (' . trim(mysql_result($res2, 0, 'description')) . ')<br /><br />';
}
}
?>
</td>
</tr>
<tr>
<td width="100%" colspan="5" align="center">
<hr style="width: 100%" />
</td>
</tr>
<?php } ?>
<?php } else { ?>
<tr>
<td width="100%" align="center">
There are currently no complete orders.
</td>
</tr>
<?php } ?>
</table>
Thanks in advance, I think I've included everything that is relative but if anything else is needed please let me know.
Joe

Try this:
$sql2 = 'SELECT * FROM products_full WHERE id = '.$tmpProdInfo[1].'';
if (count($res2) > 0)
Also, be aware when you want to use MySQL_num_rows you should include the connection. see the manual:
$link = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $link);
$result = mysql_query("SELECT * FROM table1", $link);
$num_rows = mysql_num_rows($result);

Related

Issues with mySQLi and PHP

I'm trying to create a internal messaging system.
My code is below:
$useraccess = $loggedInUser->username;
$sql = "SELECT id, user_name FROM ".$db_table_prefix."users WHERE user_name='$useraccess'";
$query = $mysqli->query($sql) or die ("Error");
while ($row = mysqli_fetch_array($query)) {
$pid = $row["id"];
$username = $row["user_name"];
}
$query->close();
$sqlCommand = "SELECT COUNT(id) AS numbers FROM ".$db_table_prefix."messages_inbox WHERE userid='$pid'";
$query = $mysqli->query($sql) or die ("Error");
$result = mysqli_fetch_assoc($query);
$inboxMessages = $result['numbers'];
?>
<h1>Inbox</h1>
<?php
$sql="SELECT * FROM ".$db_table_prefix."messages_inbox WHERE userid='$pid' ORDER by id DESC";
$result=$mysqli->query($sql);
$count=mysqli_stmt_num_rows($result);
?>
<p>
<table width="500" border="0" cellspacing="0" cellpadding="0">
<tr>
<th style="text-align: left; ">Title</th>
<th style="text-align: right; ">Sender</th>
<th style="text-align: right; "><b>Actions</b></th>
</tr>
<?php
while($rows=mysqli_field_count($result)) {
?>
<?php if ($rows['viewed'] == 0) { // show messages in bold?>
<tr>
<td style="text-align: left; "><b><?php echo $rows['title']; ?></b></td>
<td style="text-align: right; "><?php echo $rows['from_username']; ?></td>
<td style="text-align: right; ">Delete</td>
</tr>
<?php } else if ($rows['viewed'] == 1) { ?>
<tr>
<td style="text-align: left; "><?php echo $rows['title']; ?></td>
<td style="text-align: right; "><?php echo $rows['from_username']; ?></td>
<td style="text-align: right; ">Delete</td>
</tr>
<?php } ?>
<?php } ?>
</table>
<?php if ($inboxMessages > 0) { ?>
<?php } else
{ print "<div id=\"errors\">Currently you do not have messages in your Inbox</div>";
} ?>
This is the inbox in which I'm trying to show data from the DB. It connects no problem otherwise it would throw up the Error, so I believe it's my syntax.
I receive the following errors.
Warning: mysqli_stmt_num_rows() expects parameter 1 to be mysqli_stmt, object given in /opt/lampp/htdocs/project/inbox.php on line 28
Warning: mysqli_field_count() expects parameter 1 to be mysqli, object given in /opt/lampp/htdocs/project/inbox.php on line 38
Notice: Undefined index: numbers in /opt/lampp/htdocs/project/inbox.php on line 20
Use mysqli_num_rows instead, as follows:
$count=mysqli_num_rows($result);
Reference documentation: http://php.net/manual/en/mysqli-result.num-rows.php
To use mysqli_stmt_num_rows you need to change a few lines from what you have:
$sql="SELECT * FROM ".$db_table_prefix."messages_inbox WHERE userid='$pid' ORDER by id DESC";
if ($stmt = $mysqli->prepare($sql)) {
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$count = mysqli_stmt_num_rows($stmt)
$stmt->close();
}
And here is the documentation for mysqli_stmt_num_rows: http://php.net/manual/en/mysqli-stmt.num-rows.php

PHP dynamic page not working

I have a page that takes an SKU from a database and creates a page. Example URL: http://example.com/index.php?sku=1234567
When I load a URL like this, it shows nothing - not even the table which I output with echo. Below is my code:
$sku = $_GET['sku'];
$result = mysqli_query($conn, "SELECT productname, price, producturl, productimg, productdesc, sku FROM table WHERE sku=" . $sku);
while ($row = mysqli_fetch_array($result)) {
echo '<h3>test</h3>';
echo '<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td><h4>'.$row["sku"].'</h4></td>
<td><h3>'.$row["productname"].'</h3></td>
<td rowspan="2"><img src="'.$row["productimg"].'" width="100%" alt="productimg"/></td>
</tr>
<tr>
<td colspan="2" rowspan="2"><p>'.$row["productdesc"].'</p></td>
</tr>
<tr>
<td><a class="button" href="'.$row["producturl"].'">View Product</a> <a class="alert button" href="">No Match</a> <a class="alert button" href="">Match</a></td>
</tr>
</table>';
}
I have connected to my database and have the <?php and ?> tags in there. I have noticed while playing around with it that if I remove this line:
while ($row = mysqli_fetch_array($result)) {
and also remove the closing }, it works but does not display any data - just the table. I am not sure what is going on here.
Simple. your mysqli_query call returns no records. Either no records are found, or there is an error. Make your code a little more robust.
$sku = $_GET['sku'];
if ($result = mysqli_query($conn, ...)) {
if (mysqli_num_rows($result) == 0) {
echo "no skus found";
} else {
while ($row = mysqli_fetch_array($result)) {
echo '<h3>test</h3>';
...
}
}
} else {
echo "something went wrong: ".mysqli_error();
}
(As a side note, please use parametrised queries, you are opening yourself up to SQL injection now. MySQLi is no magic bullet against this, you still have to validate / sanitize input.)
Display mysqli error on fault:
if (!mysqli_query($link, $sql)) {
printf("Errormessage: %s\n", mysqli_error($link));
}
Put $sku inside quotes.
<?php
$sku = $_GET['sku'];
$result = mysqli_query($conn, "SELECT productname, price, producturl, productimg, productdesc, sku FROM table WHERE sku = $sku");
while ($row = mysqli_fetch_array($result)) {
echo '<h3>test</h3>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td><h4>'.$row["sku"].'</h4></td>
<td><h3>'.$row["productname"].'</h3></td>
<td rowspan="2"><img src="'.$row["productimg"].'" width="100%" alt="productimg"/></td>
</tr>
<tr>
<td colspan="2" rowspan="2"><p>'.$row["productdesc"].'</p></td>
</tr>
<tr>
<td><a class="button" href="'.$row["producturl"].'">View Product</a> <a class="alert button" href="">No Match</a> <a class="alert button" href="">Match</a></td>
</tr>
</table>';
}
?>
I have managed to solve the issues that i have been having i had to remove the i from mysqli, but i have used the same piece of code on another site so it may be something to do with the server or database maybe. here is the code though'
<?php
$sku = $_GET['sku'];
$objConnect = mysql_connect("host address","username","password") or die(mysql_error() . 'this is true death...');
$objDB = mysql_select_db("database");
$result = 'SELECT sku, productname, price, producturl, productimg, productdesc FROM table1 WHERE sku="' . $sku . '"';
$result = mysql_query($result);
while ($row = mysql_fetch_array($result)) {
echo '<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td><h4>'.$row["sku"].'</h4></td>
<td><h3>'.$row["productname"].'</h3></td>
<td rowspan="2" width="30%"><img src="'.$row["productimg"].'" width="100%" alt="productimg"/></td>
</tr>
<tr>
<td colspan="2" rowspan="2"><p>'.$row["productdesc"].'</p></td>
</tr>
<tr>
<td><a class="button" href="'.$row["producturl"].'">View Product</a> <a class="alert button" href="">No Match</a> <a class="alert button" href="">Match</a></td>
</tr>
</table>';
}
?>

error: Notice: Undefined offset: 1 in C:\wamp\www\project\php\deleteRow.php on line 55

I got this error when trying to delete emails from a table form and database,,i tried to solved it but some fields work while others still gives me an error, any help is apreciated,,i am learning php on my own.
/here is my code/
<?php
$dbhost = 'host';
$dbuser = 'username';
$dbpass = 'password';
$dbname = 'databe_name';
$dbtable = 'database_table';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
//
mysql_select_db($dbname,$conn) or die ("Could not open database");
//
$sql="SELECT * FROM '$dbtable'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
?>
<table width="400" border="0" cellspacing="1" cellpadding="0">
<tr>
<td><form name="form1" method="post" action="">
<table width="400" border="0" cellpadding="3" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<td bgcolor="#FFFFFF"> </td>
<td colspan="4" bgcolor="#FFFFFF"><strong>Delete multiple rows in mysql</strong> </td>
</tr>
<tr>
<td align="center" bgcolor="#FFFFFF">#</td>
<td align="center" bgcolor="#FFFFFF"><strong>Id</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Sender</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Message</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Date</strong></td>
</tr>
<?php
while($rows=mysql_fetch_array($result)){
?>
<tr>
<td align="center" bgcolor="#FFFFFF"><input name="checkbox[]" type="checkbox" id="checkbox[]" value="<?php echo $rows['id']; ?>"></td>
<td bgcolor="#FFFFFF"><?php echo $rows[0]; ?></td>
<td bgcolor="#FFFFFF"><?php echo $rows[2]; ?></td>
<td bgcolor="#FFFFFF"><?php echo $rows[3]; ?></td>
<td bgcolor="#FFFFFF"><?php echo $rows[4]; ?></td>
</tr>
<?php
}
?>
<tr>
<td colspan="5" align="center" bgcolor="#FFFFFF"><input name="delete" type="submit" id="delete" value="Delete"></td>
</tr>
<?php
// Check if delete button active, start this
if(isset($_POST['delete'])){
for($i=0;$i<$count;$i++){
$del_id = $_POST['checkbox'][$i]; /*this line gives me an error*/
$sql = "DELETE FROM '$dbtable' WHERE id='$del_id'";
$result = mysql_query($sql);
}
// if successful redirect to delete_multiple.php
if($result){
echo "<meta http-equiv='refresh' content='0' URL='deleteRow.php'>";
}
}
mysql_close();
?>
</table>
</form>
</td>
</tr>
Try:
if(isset($_POST['delete'])){
$checkboxCount = count($_POST['checkbox']);
for($i=0;$i<$checkboxCount;$i++){
$del_id = $_POST['checkbox'][$i];
$sql = "DELETE FROM '$dbtable' WHERE id='$del_id'";
$result = mysql_query($sql);
}
// if successful redirect to delete_multiple.php
if($result){
echo "";
}
}
Unchecked checkboxes do not have their value sent.
You probably need to replace your for body with:
if(isSet($_POST['checkbox'][$i])) {
$del_id = $_POST['checkbox'][$i]; /*this line gives me an error*/
$sql = "DELETE FROM '$dbtable' WHERE id='$del_id'";
$result = mysql_query($sql);
}
checkbox post fields are only available in the post when checked. so your post array can contain only values 1 and 2. you loop through all your db rows change your $count variable in the count of the checkbox array
$_POST['checkbox'][1] does not exist.
instead of using $count which is the number of query results in your code, use count($_POST['checkbox'])
So for($i=0;$i<$count;$i++){ would become
for($i=0; $i < count($_POST['checkbox']); $i++){
And on a second look, like others have suggested, not all indices of the checkbox may be set. It is better to use a foreach loop where you can get the key and value easily.
foreach($_POST['checkbox'] as $key => $value){
When a checkbox is not checked it won't show up in $_POST['checkbox'].
What you can do is to save all checked boxes in an array and after the loop execute a single delete query for all checked boxes.
for($i=0;$i<$count;$i++){
if (isset($_POST['checkbox'][$i])) $delids[] = $_POST['checkbox'][$i];
}
if (isset($delids) && is_array($delids)) {
$sql = "DELETE FROM '$dbtable' WHERE id IN (".implode(',', $delids).")";
$result = mysql_query($sql);
}
But a better way would be to skip your for-loop and use foreach instead like this:
foreach($_POST['checkbox'] as $c) {
$delids[] = $c;
}
if (isset($delids) && is_array($delids)) {
$sql = "DELETE FROM '$dbtable' WHERE id IN (".implode(',', $delids).")";
$result = mysql_query($sql);
}
I think the confusion lies in the fact that you're using the value ($count - the number of rows) to index into the value for each checkbox. The number of rows defines how many checkboxes there will be, but not the value of each checkbox. Hence $i in the delete loop is not guaranteed to be less than the size of the checkbox array.

How can I get it so at the top of my search results page it says the amount of results found?

I have a results page and I would like there to be a bit at the top of the page where it says how many results were returned. How do I do this?
My code is
<?php
if(strlen(trim($_POST['search'])) > 0) {
$search = "%" . $_POST["search"] . "%";
$searchterm = "%" . $_POST["searchterm"] . "%";
mysql_connect ("3", "", "");
mysql_select_db ("");
if (!empty($_POST["search_string"]))
{
}
$query = "SELECT name,location,msg FROM contact WHERE name LIKE '%$search%' AND
location LIKE '%$searchterm%'";
$result = mysql_query ($query);
if ($result) {
while ($row = mysql_fetch_array ($result)) { ?>
<center>
<table height="20" width="968" cellpadding="0" cellspacing="0">
<tr>
<td>
<table height="20" width="223" cellpadding="0" cellspacing="0">
<tr>
<td>
<font face="helvetica" size="2" color="#045FB4"><?php echo $row[0]; ?></font>
<hr size="1" color="#e6e6e6" width="100%"></hr>
</td>
</tr>
</table>
</td>
<td>
<table height="20" width="745" cellpadding="0" cellspacing="0">
<tr>
<td>
<font face="helvetica" size="2" color="black"><?php echo $row[1]; ?>
<?php echo $row[2]; ?></font>
<hr size="1" color="#e6e6e6" width="100%"></hr>
<td align="right">
<font face="helvetica" size="2" color="red">See More...</font>
<hr size="1" color="#e6e6e6" width="100%"></hr>
</td>
</tr>
</table>
</td>
</tr>
</table>
<?php
}
}
}
?>
</center>
THANKS!
James
If you're going to keep it to one page then mysql_num_rows() will do the trick and you're good to go. If you use pagination on the other hand, then your SELECT query will have a LIMIT clause and a second query can be constructed using COUNT(*) on the same tables with the same WHERE clause.
$total_query = "SELECT COUNT(*) FROM contact WHERE name LIKE '%$search%' AND
location LIKE '%$searchterm%'"
I’m not trying to compete with the other fine answers. I’m posting this as an answer because it’s too big for a comment.
Since you asked in a comment what could be done to improve your HTML, I refactored your code a bit just to illustrate some things you could do. I also included mysql_num_rows($result) mentioned by the others for the sake of completion.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Sample</title>
<style type="text/css">
table {
font-family: helvetica;
font-size: small;
width: 968px;
}
td {
border-bottom: 1px solid #e6e6e6;
}
.name {
color:#045FB4;
}
.msg {
color:black;
}
.more {
color:red;
}
</style>
</head>
<body>
<?php
if(strlen(trim($_POST['search'])) > 0):
$search = mysql_real_escape_string($_POST["search"]);
$searchterm = mysql_real_escape_string($_POST["searchterm"]);
mysql_connect ("localhost", "root", "");
mysql_select_db ("sample");
if (!empty($_POST["search_string"]))
{
$search_string = mysql_real_escape_string($_POST["search_string"]);
// more code here
}
$query = "SELECT name,location,msg FROM contact
WHERE name LIKE '%$search%'
AND location LIKE '%$searchterm%'";
$result = mysql_query ($query);
if ($result):
$num_rows = mysql_num_rows($result);
?>
<p>Found <?php echo $num_rows; ?> results.</p>
<table>
<?php
while ($row = mysql_fetch_array ($result)):
?>
<tr>
<td class="name"><?php echo $row['name']; ?></td>
<td class="msg"><?php echo $row['location'], ' ', $row['msg']; ?></td>
<td class="more">See More...</td>
</tr>
<?php
endwhile;
endif;
endif;
?>
</table>
</body>
</html>
Normally, I would put the CSS in a separate file, but this is only an example.
Some things to notice:
There’s only one table
There’s no style information in the HTML
It uses mysql_real_escape_string. Ideally you'd also want to use prepared statements, but I’ll leave that as a personal exercise for you. :)
Even this can be improved quite a bit, but it's a start.
Try using mysql_num_rows($query). I am no PHP expert but, from memory, that should do the trick. Just echo this wherever you want it.
$num_rows = mysql_num_rows($result);
Check out the documentation: http://php.net/manual/en/function.mysql-num-rows.php
Also you can use SQL_CALC_FOUND_ROWS and FOUND_ROWS():
$query = "SELECT SQL_CALC_FOUND_ROWS name,location,msg FROM contact WHERE name LIKE '%$search%' AND location LIKE '%$searchterm%'";
$result = mysql_query($query);
if ($result)
{
$rs_count = mysql_query("SELECT FOUND_ROWS();");
$counted = (int)mysql_result($rs_count, 0);
}

php Multiple looping problem

Im writing a function to get the parent and child ids but for the third loop there is a
problem the loop gets even the previous loops id also .
How can i avoid it?
<?
$results = '
<table>
<thead>
<tr >
<td id="ticket" align="center" ><b>Task<br />ID</b></td>
<td id="ticket" align="center" ><b>col1</td>
<td id="ticket" align="center" ><b>col2</td>
</tr>
</thead>
<tbody>';
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC))
{
$results .='
<tr >
<td align="center">
'.$row['Task_id'].'
</td>';
$results .= '<td align="center">';
$gg = mysqli_query($dbc,"select * from Tasks where ParentTask_Id='".$row['Task_id']."'");
echo "<br>";
while ($rowdd = mysqli_fetch_assoc($gg))
{
$results .= $rowdd['Task_id']."<br><br>";
$gg2 = mysqli_query($dbc,"select * from Tasks where ParentTask_Id='".$rowdd['Task_id']."'");
while ($rowdd2 = mysqli_fetch_assoc($gg2))
{
$results2 = $rowdd2['Task_id']."<br><br>";
}
echo "<br>";
}
// $results .= $car ;
// $results .= $t;
$results .='</td>';
$results .=' <td align="left" >'?>
<?
$results .= $results2;
$results .='</td>';
$results .='
</tr>';
}
?>
Is the $results variable empty? I only see it being concatenated.
Also, on your table you have multiple ids that are the same. You either need to change that to a class or have a unique value for each id.

Categories