PHP dynamic page not working - php

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>';
}
?>

Related

How to get Data from HTML Table

I am developing a project in which I have an admin and users so in the admin panel I have a table in which all videos and All User are listed With checkBox.
In the table, I have Two columns Videos and Users. In videos column, all videos are listed and in the Users column, there is another table called Select User where all users are listed with a checkbox for each video.
So the problem is when admin selects the user's checkbox I want to know for which video he selects the users so that specific video only appear to selected users in the user panel.
image link for user table
link: https://ibb.co/t25kppy
I hope you all understand my problem
I am able to the selected user's name from checkbox but don't know how to get the video for which the users are selected
<?php
require_once 'Header.php';
require_once 'Includes/DB.php';
$query = 'SELECT * FROM `videos`;';
$query2 = 'SELECT `FullName` FROM `users`;';
$result = mysqli_query($conn, $query);
$result2 = mysqli_query($conn, $query2);
$checkResult = mysqli_num_rows($result);
$checkResult2 = mysqli_num_rows($result2);
while ($row2 = mysqli_fetch_assoc($result2)) {
$data[] = $row2['FullName'];
?>
<main>
<div class="container">
<table class="table">
<thead>
<tr>
<th scope="col"><h4 align="center">Videos</h4></th>
<th scope="col"><h4 align="center">Users</h4></th>
</tr>
</thead>
<tbody>
<?php
if ($checkResult > 0 && $checkResult2 > 0)
{
while ($row = mysqli_fetch_assoc($result))
{
echo '
<tr>
<form action="Select_Users.php" method="post">
<td align="center" scope="row"> <iframe width="200" height="200" src="https://www.youtube.com/embed/' . $row['youtube_video_id'] . '"frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</td>
<td>
<table class="table">
<thead>
<th scope="col"><h4 align="left">Select Users</h4></th>
</thead>
<tbody>
<tr>
<td>';
for ($i = 0; $i < count($data); $i++)
{
echo '<div><label><input type="checkbox" name="selectedUsers[]" value="' . $data[$i] . ' ">' . $data[$i] . '</label></div> <br><br>';
}
echo'
<button type="submit" name="Submit"> Submit</button>
</td>
</form>
</tr>
</tbody>
</table>
</td>';
}
}
else
{
echo 'no result fount in database';
}
?>
</tbody>
</table>
</form>
</div>
<?php
if (isset($_POST['Submit']))
{
if (!empty($_POST['selectedUsers']))
{
foreach ($_POST['selectedUsers'] as $selectedUsers)
{
echo '<h1>'.$row['youtube_video_id'].'</h1>';
echo '<h1>'.$selectedUsers.'</h1>';
}
}
else
{
echo '<h1>No value found</h1>' ;
}
}
?>
Send the video id using query parameters:
<form action="Select_Users.php?youtube_id='.$row['youtube_video_id'].'" method="post">
Then retrieve it like so:
<?php
if (isset($_POST['Submit']))
{
if (!empty($_POST['selectedUsers']))
{
foreach ($_POST['selectedUsers'] as $selectedUsers)
{
$youtube_id = $_GET['youtube_id'];
echo '<h1>'.$youtube_id.'</h1>';
echo '<h1>'.$selectedUsers.'</h1>';
}
}
else
{
echo '<h1>No value found</h1>' ;
}
}
?>
Just add a hidden input with the video id in each form, name that input so that you can read the value from $_POST, just like what you did with the users.

PHP and MYSQL: Insert input select with mysql data and show all other fields when change selection

I have this situation:
The table of my database is called reteconsolare and have these fields:
ID
Stato
Citta
Indirizzo
Telefono
Email
URL
Mappa
Descrizione (This is not really show. I use it only for showing the title of the images on Sito & Mappa links)
In this moment all works ok, just that When there are more "Citta" for "Stato" I wish that in the "Citta" colum would appear an input select with all the available name of the Citta for Stato ordering from A to Z and when changing the selection, should also show the correct Indirizzo, Telefono, Email, URL, Mappa.
Following is my actual code that repeat the values.
eg.:
Belgio | Bruxelles
Belgio | Charleroi
<?Php
mysqli_set_charset($connessione, 'utf-8');
$sql = "SELECT * FROM reteconsolare ORDER BY Stato, Citta";
$query = $connessione->query($sql) ;
while ($row = $query->fetch_assoc()) {
$stato=sprintf( $row["Stato"]);
$citta=sprintf( $row["Citta"]);
$indirizzo=sprintf( $row["Indirizzo"]);
$descrizione=sprintf( $row["Descrizione"]);
$email=sprintf( $row["Email"]);
$telefono=sprintf( $row["Telefono"]);
$mappa=sprintf( $row["Mappa"]);
$link=sprintf( $row["URL"]);
$id=sprintf( $row["ID"]);
?>
<tr>
<td width="20%"><ts><?Php echo($stato) ?></ts></td>
<td width="20%"><ts><?Php echo($citta) ?></ts></td>
<td width="30%"><ts><?Php echo($indirizzo) ?></ts></td>
<td width="10%"><ts><?Php echo($telefono) ?></ts></td>
<td width="10%"><ts><?Php echo emailize($email) ?></ts></td>
<td width="5%" align="center"><?Php echo(' <a target=_blank href='); echo($link); echo('>'); ?><img src="img/www.png" width="20" height="20" title="Link al sito del <?php echo ($descrizione);?>"></a></td>
<td width="5%" align="center"><?Php echo(' <a target=_blank href='); echo($mappa); echo('>'); ?><img src="img/Maps.png" width="20" height="20" title="Mappa del <?php echo ($descrizione);?>"></a></td>
</tr>
<?php } while ($row_news = $query->fetch_assoc());?>
<?php
function emailize($text)
{
$regex = '/(\S+#\S+\.\S+)/';
$replace = '$1';
return preg_replace($regex, $replace, $text);
}?>
I searched also an alternative way: not repeating the name of the Stato and Wrap every city with its data. I tried to play with mysql's group by... but without results. And anyway don't really like too much this solution. I think that i need to know maybe also Ajax to solve this problem, but at the moment i can't learn it...Thanks in advance.
You can do one thing: store "Stato" in array and check if the value already exist in array or not. For i.e. :
<?Php
mysqli_set_charset($connessione, 'utf-8');
$sql = "SELECT * FROM reteconsolare ORDER BY Stato, Citta";
$query = $connessione->query($sql) ;
$Stato = array() ;
while ($row = $query->fetch_assoc()) {
if(!in_array(sprintf($row["Stato"]),$Stato)){
$stato=sprintf( $row["Stato"]);
$Stato = sprintf( $row["Stato"]);
$citta=sprintf( $row["Citta"]);
$indirizzo=sprintf( $row["Indirizzo"]);
$descrizione=sprintf( $row["Descrizione"]);
$email=sprintf( $row["Email"]);
$telefono=sprintf( $row["Telefono"]);
$mappa=sprintf( $row["Mappa"]);
$link=sprintf( $row["URL"]);
$id=sprintf( $row["ID"]);
?>
<tr>
<td width="20%"><ts><?Php echo($stato) ?></ts></td>
<td width="20%"><ts><?Php echo($citta) ?></ts></td>
<td width="30%"><ts><?Php echo($indirizzo) ?></ts></td>
<td width="10%"><ts><?Php echo($telefono) ?></ts></td>
<td width="10%"><ts><?Php echo emailize($email) ?></ts></td>
<td width="5%" align="center"><?Php echo(' <a target=_blank href='); echo($link); echo('>'); ?><img src="img/www.png" width="20" height="20" title="Link al sito del <?php echo ($descrizione);?>"></a></td>
<td width="5%" align="center"><?Php echo(' <a target=_blank href='); echo($mappa); echo('>'); ?><img src="img/Maps.png" width="20" height="20" title="Mappa del <?php echo ($descrizione);?>"></a></td>
</tr>
<?php }} while ($row_news = $query->fetch_assoc());?>
<?php
function emailize($text)
{
$regex = '/(\S+#\S+\.\S+)/';
$replace = '$1';
return preg_replace($regex, $replace, $text);
}?>
Hope this will work for you.
Check syntax in while:
while ($row = $query->fetch_assoc()) {
...
} while ($row_news = $query->fetch_assoc());
Correct syntax:
while(condition) {
...
}
or
do {
...
} while(condition)

Update shopping cart

I'm pretty new to PHP, just followed a course and working on my final case to get a certificate. We're working on a webstore and I'm having trouble with updating my shopping cart. I know that this question has been asked before, but after reading through the answers, I can't fix my own code. I hope someone can help me with this.
If there's 1 item in the cart, it updates well, with more items, just one 1 item will be updated. Here's my shopping cart code (it's been EDITED since first post to be more complete):
<FORM method=get name=cart_quantity
action=winkelwagen.php>
<TABLE border=0 cellSpacing=0 cellPadding=0 width="100%">
<TBODY>
<TR>
<TD>
<TABLE class=productListing border=0 cellSpacing=0
cellPadding=2 width="100%">
<TBODY>
<TR>
<TD class=infoBoxHeading3 align=middle>Verwijder</TD>
<TD class=infoBoxHeading3>Artikel(en)</TD>
<TD class=infoBoxHeading3 align=middle>Aantal</TD>
<TD class=infoBoxHeading3
align=right>Totaal </TD></TR>
<?php
$sqlWinkelwagen = "SELECT * FROM tblorder
INNER JOIN tblorderregels
INNER JOIN tblartikelen
WHERE tblorder.Ordernummer = tblorderregels.Ordernummer AND SessieID = '" . session_id() . "' AND tblorderregels.Artikelnummer = tblartikelen.Artikelnummer";
$rsWinkelwagen = mysqli_query($db, $sqlWinkelwagen);
$WinkelwagenRegel = 0;
while ($rWinkelwagen = mysqli_fetch_array($rsWinkelwagen))
{
?>
<TR class=productListing-even>
<TD class=productListing-data vAlign=top
align=middle><br><br>
<img border="0" src="images/bin.png" width="30" height="30">
<input type=hidden name=Artikelnummer value=<?php echo($rWinkelwagen["Artikelnummer"]);?>>
<TD class=productListing-data><BR>
<TABLE border=0 cellSpacing=2 cellPadding=2>
<TBODY>
<TD class=productListing-data align=middle><A
href="http://www.mijnoscommerce.nl/demo/shop1/product_info.php?products_id=35{1}1"><IMG
title=" iPhone 3G - 8GB " border=0
alt="iPhone 3G - 8GB"
src="images/<?php echo($rWinkelwagen["Afbeelding"]);?>" width=100
height=80></A></TD>
<TD class=productListing-data vAlign=top><BR><A
href="http://www.mijnoscommerce.nl/demo/shop1/product_info.php?products_id=35{1}1"><B>
<?php echo($rWinkelwagen["Artikelnaam"]); ?>
</B></A> </TD></TR></TBODY></TABLE></TD>
<TD class=productListing-data vAlign=top
align=middle><BR><BR><INPUT
type="text" value=<?php echo($rWinkelwagen["Aantal"]); ?> size=4
name=AantalArtikel[<?php echo($rWinkelwagen["Artikelnummer"]);?>]
>
<input type=hidden
name=ArtikelID[<?php echo($rWinkelwagen["Artikelnummer"]);?>]
value=<?php echo($rWinkelwagen["Artikelnummer"]);?>
>
<input type=hidden name=action value=upd></TD>
<TD class=productListing-data vAlign=top
align=right><BR><BR><B>Ä
<?php
$TotaalArtikel = $rWinkelwagen["Aantal"] * $rWinkelwagen["Prijs"];
echo($TotaalArtikel);
$TotaalWinkelwagen = $TotaalWinkelwagen + $TotaalArtikel;
?>
</B> </TD>
<?php
} //einde while winkelwagen inhoud
mysqli_free_result($rsWinkelwagen);
?>
</TBODY></TABLE></TD></TR>
<TR>
<TD><IMG border=0 alt=""
src="winkelwagen_files/pixel_trans.gif" width="100%"
height=10></TD></TR>
<TR>
<TD class=main align=right><B>Subtotaal: Ä <?php echo($TotaalWinkelwagen); ?>
</B> </TD></TR>
<TR>
<TD class=stockWarning align=middle><BR>Artikelen met een: ***
Zijn momenteel niet besckikbaar in de door u gevraagde
hoeveelheid.<BR>U kan de geselecteerde hoeveelheid wel laten
staan en bij het afrekenen zal de beschikbare hoeveelheid
getoond worden.</TD></TR>
<TR>
<TD><IMG border=0 alt=""
src="winkelwagen_files/pixel_trans.gif" width="100%"
height=10></TD></TR>
<TR>
<TD>
<TABLE class=infoBox2 border=0 cellSpacing=1 cellPadding=2
width="100%">
<TBODY>
<TR class=infoBoxContents>
<TD>
<TABLE border=0 cellSpacing=0 cellPadding=2 width="100%">
<TBODY>
<TR>
<TD width=10><IMG border=0 alt=""
src="winkelwagen_files/pixel_trans.gif" width=10
height=1></TD>
<TD class=main><INPUT title=" Update Winkelwagen "
border=0 alt="Update Winkelwagen"
src="winkelwagen_files/button_update_cart.gif"
type=image
></TD>
<TD class=main><A
href="index.php"><IMG
title=" Verder winkelen " border=0
alt="Verder winkelen"
src="winkelwagen_files/button_continue_shopping.gif"
width=129 height=16></A></TD>
<TD class=main align=right><A
href="betalingswijze.php"><IMG
title=" Afrekenen " border=0 alt=Afrekenen
src="winkelwagen_files/button_checkout.gif"
width=86 height=16></A></TD>
<TD width=10><IMG border=0 alt=""
src="winkelwagen_files/pixel_trans.gif" width=10
height=1></TD></TR></TBODY></TABLE></TD></TR></TBODY></TABLE></TD></TR></TBODY></TABLE></FORM>
After applying the form it returns to the same page, on top with this code:
<?php
require_once 'config.php';
$db = mysqli_connect($strDatabaseServer, $strUsername, $strPassword, $strDatabase);
if(!$db)
die('Fout bij verbinden met database: ' . mysqli_connect_error());
$sql = "SELECT * FROM tblorder where SessieId = '" . session_id() . "'";
if(!$rs = mysqli_query($db, $sql))
die('Fout in query: ' . mysqli_error());
if (mysqli_num_rows($rs) > 0)
{
$r = mysqli_fetch_array($rs);
$intOrdernummer = $r["Ordernummer"]; // bestaande ordernr
mysqli_free_result($rs);
}
//echo ($intOrdernummer);
if (isset($_GET["action"]))
{
switch ($_GET["action"])
{
case "del":
$strSQL = "delete from tblorderregels where Artikelnummer = '" . $_GET["Artikelnummer"] . "' AND Ordernummer = $intOrdernummer";
break;
case "upd":
foreach($_GET['ArtikelID'] as $key => $id){
$Artikelnummer = $id;
$aantal = $_GET['AantalArtikel'][$key];
//$sql2 = "update orders SET quantity = '$quantity' where item_id = '$item_id' ";
$strSQL = "update tblorderregels set Aantal = '" . $aantal . "' where Artikelnummer = '" . $Artikelnummer . "' AND Ordernummer = $intOrdernummer";
}
break;
}
$intGoed = mysqli_query($db, $strSQL);
if (!$intGoed)
die("Foutje in de SQL: " . $strSQL);
}
?>
I tried to make unique variables with GET, but somehow it isn't working
I hope some one can help with this, thanks in advance!
To confirm:
4th line of the html is a link that will give GET variables of $_GET['Artikelnummer'] = Artikelnummer and $_GET['action'] = del if you click the link
Final line of the html is a hidden input that will give a GET variable (since no method specified in the form element) of $_POST['action'] = upd, there is a hidden input for the Artikelnummer, and a text input for the number. You get this if you submit the form (there is no submit button in your current html)
Things that work:
If single/multiple item(s), clicking the delete link would just delete the one item you clicked for
If a single item, updating the name=AantalArtikel text input with the new number and submitting the form would update that item
Problems:
If multiple items, there is no way to tell which name=AantalArtikel text input refers to which Artikelnummer
Solution:
A separate form for each product that you want to update so multiple submit buttons
Or, each name=AantalArtikel text input must have a unique name e.g. name=AantalArtikel-Artikel1
Tip:
use print_r($_GET) to view what the form/link output is to see where you are going wrong
Additional Comments:
The rough format would be:
HTML
form
hidden input action="upd"
hidden input name="number_of_items" value="2"
product1 html
hidden input name="product1_name" value="red_car"
text input name="product1_number" value="1"
link ?product_name=NAME1&action=del
product2 html
hidden input name="product2_name" value="blue_car"
text input name="product2_number" value="1"
link ?product_name=NAME2&action=del
submit button
PHP
if GET action=del
-> sanitise input, delete product
if GET action=upd
-> for (i <= GET number_of_items)
-> sanitise input, get variables using $i in the name to loop through the numbers
I fixed the problem. The mysql query was not in my switch, so that's why the sql query was not being performed well.
Thanks for helping!

php explode product array throwing up errors

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

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.

Categories