Deleting database values Using PHP, not working - php

I am trying to delete multiple values from my form (its a car rental system, where I want to give the staff the ability to delete a car from the record). I am new to PHP but this is what I have right now.
<?php
$link = mysql_connect ("xxxx", "xxxx", "xxxx");
mysql_select_db ("xxxx");
$query = "SELECT * from car";
$result = mysql_query ($query);
echo ("<form action=\"deleting2.php\" method=\"GET\">");
echo "<table id = 'table-3'>";
echo "<thead>";
echo "<th>Car ID</th>
<th>Car Name</th>
<th>Fuel Type</th>
<th>Transmission</th>
<th>Engine Size</th>
<th>Doors</th>
<th>Total</th>
<th>Available</th>
<th>Date Added</th>
<th>Delete</th> ";
echo "</thead>";
for ($i = 0; $i < mysql_num_rows ($result); $i ++)
{
$row = mysql_fetch_object ($result);
echo "<tbody>";
echo "<tr>";
echo "<td>$row->ID</td>";
echo "<td>$row->CARNAME</td>";
echo "<td>$row->FUELTYPE</td>";
echo "<td>$row->TRANSMISSION</td>";
echo "<td>$row->ENGINE_SIZE</td>";
echo "<td>$row->DOORS</td>";
echo "<td>$row->TOTAL</td>";
echo "<td>$row->AVAILABLE</td>";
echo "<td>$row->DATEADDED</td>";
echo "<td><input type='checkbox' name='delete[]' value='$row->ID' /></td>";
echo "</tr>";
echo "</tbody>";
}
echo ("<tr><td colspan='6' align='center'><input type=\"submit\" value=\"Delete \"></td> </tr></table></form>");
echo "</table>";
mysql_close ($link);
?>
Now,when I do press the delete button, it goes to my php page called 'deleting2.php' as mentioned in the form action, which has the following code:
<?php
$link = mysql_connect ("xxxx", "xxxx", "xxxx");
mysql_select_db ("xxxx");
$ID='$_GET[ID]';
// DELETE ANY RECORDS IN DATABASE
for ($i = 0; $i < #mysql_num_rows ($result); $i ++)
{
if(isset($_GET['delete[]']) && $_GET['delete[]']=='$row->ID');
{
$query=("DELETE FROM car WHERE ID='$_POST[ID]'");
$result1 = mysql_query($query);
}
}
mysql_close ($link);
?>
The problem is, it is NOT deleting anything from the my database. The URL in the address bar when the deleting2.php is being processed, is:
http://www.computing.northampton.ac.uk/~11430900/a1/webpages/deleting2.php?delete[]=6
Which according to my knowledge, selects the values that were ticket. Here, I had checked the box, which had a corresponding ID value of 6. So, check-box DOES work, it just does not do anything to the database, does not delete the value. I have tried many tutorials but I can't delete it using check-boxes. Any help would be much appreciated.

You don't need to itrate through following loop as mentioned in your question
for ($i = 0; $i < #mysql_num_rows ($result); $i ++)
{
if(isset($_GET['delete[]']) && $_GET['delete[]']=='$row->ID');
{
$query=("DELETE FROM car WHERE ID='$_POST[ID]'");
$result1 = mysql_query($query);
}
}
mysql_close ($link);
just to the following.
change your form method to POST.
use the following code. implode is necessary as $_POST['delete'] will be an array
if(isset($_POST['delete']) && count($_POST['delete']) > 0) {
$query=("DELETE FROM car WHERE ID in ('".implode(',',$_POST['delete'])."')");
$result1 = mysql_query($query);
}

Your data needs sanitizing but this should be Ok if you expect the ID to be a number:
$id = (int)$_GET['ID'];
$query=("DELETE FROM car WHERE ID=$id");
You really need to look at the rest of your code for SQL injection attacks.

First of all, be very carefull when implementing a database entries deletion as You could end up with empty database.
Secondly, always sanitize Your input to prevent SQL Injection.
Thirdly, learn PDO or at least mysqli_* functions instead of mysql_ as they are deprecated now and could be removed with any next PHP release.
Now, to Your problem, You are setting the ID values into a delete[] array value, that means You should do this:
// DELETE THE DESIRED RECORDS IN DATABASE
foreach($_GET['delete'] as $id) {
$result = mysql_query("DELETE FROM car WHERE ID = '" . mysql_real_escape_string($id) . "'");
// do something with the $result here ...
}
Other option could be to expect only integers:
// DELETE THE DESIRED RECORDS IN DATABASE
foreach($_GET['delete'] as $id) {
$result = mysql_query("DELETE FROM car WHERE ID = '" . (int)$id . "'");
// do something with the $result here ...
}

Related

PHP - How can I print out my database table?

I have a php code to print out my table including its column name. The printing has to be dynamic because it has to print different size/length tables based on a user input. :
<table>
<?php
while ($row = mysqli_fetch_array($results)) {
while ($fieldInfo = mysqli_fetch_field($results)) { ?>
<th> <?php echo $fieldInfo->name; ?> </th>
<td> <?php echo $row[$fieldInfo->name] ?> </td>
<?php }
} ?>
</table>
this is the query for $results:
$tName = $_POST["tableNames"]; //this data is recieved from another page
require_once("conn.php");
$sql = "SELECT * FROM $tName";
$results = mysqli_query($conn, $sql)
or die ('Problem with query' . mysqli_error($conn));
my code correctly prints out the table name as well as the first row data but it is not formatted correctly here is how it looks:
additionally. for some reason it only prints out the first row even though im using a while loop.
My advice to you is to prepare two arrays:
First one: containing column names and second: containing data.
When use two foreach to generate first row with header and second one to display data. You have forgot to add <tr> tags to divide rows.
Use
The mysqli_fetch_field() function returns the next column in the result set as an object. It will only returns all column names not the records of table.
You need to use mysqli_fetch_array() for getting all records:
while ($info = mysqli_fetch_array($results,MYSQLI_ASSOC)) {
{
echo $info['rid'];
echo $info['level'];
....
}
I ended up with using a taras' suggestion of storing the column names in an array:
<table>
<?php
while ($fieldInfo = mysqli_fetch_field($results)) { ?>
<th> <?php echo $fieldInfo->name; ?> </th>
<?php
$colNames[] = $fieldInfo->name;
?>
<?php }
while ($row = mysqli_fetch_array($results)) { ?>
<tr>
<?php for ($i=0; $i<sizeof($colNames); $i++) { ?>
<td><?php echo $row[$colNames[$i]] ?>
<?php } ?>
</tr>
<?php } ?>
</table>
As of my understand, do you want to display all table and their columns?
So you can format like below
$sql = "SHOW TABLES FROM dbname";
$result_tables = mysqli_query($link, $sql);
echo "<table border=1>";
echo "<tr><td>Table name</td><td>Fields name</td></tr>";
while($row = mysqli_fetch_array($result_tables)) {
echo "<tr>";
echo "<td>".$row[0]."</td>";
$sql2 = "SHOW COLUMNS FROM ".$row[0];\\row[0] is used to get table name
$result_fields = mysqli_query($link, $sql2);
echo "<td>";
while($row2 = mysqli_fetch_array($result_fields)) {
echo $row2['Field'].',';
}
echo "</td>";
echo "</tr>";
}

How to update database with entire html table (PHP, MySQL)

I have been struggling with this for several days now. I have searched on how to update tables and have managed to get as far as to update rows, but only the last one in the table. So now i am trying to get a loop that loops through all the inputs and updates the database with the inputted values. I think the code that needs to be corrected is located near the end of the code
What i want to do:
Get/display database in html table
Change values of certain columns
Update the database table using a submit button which updates every row in database
Here is a picture of what the table looks like in web view:
<?php
//Connect to database
include '../db/connect.php';
?>
<form action='test7.php' method="post">
<table border='1'>
<?php
$result = $MySQLi_CON->query("SELECT * FROM users");
echo "<tr>";
echo "<td colspan='3'>CLASS 1</td>";
echo "</tr>";
//All table rows in database presented in html table
while($row = $result->fetch_array()){
echo "<tr>";
echo "<td><input type='hidden' name='user_id[]' value='".$row['user_id']."' /></td>";
echo "<td>username :<input type='text' name='username[]' value='".$row['username']."' /></td>";
echo "<td>email :<input type='text' name='email[]' value='".$row['email']."' /></td>";
echo "<td>rank :<input type='number' name='rank[]' value='".$row['rank']."' /></td>";
echo "</tr>";
}
echo "<input type='submit' name='update' value='UPDATE' />";
?>
<table>
</form>
<?php
if(isset($_POST['update'])){
$total = count($_POST['rank']);
$user_id_arr = $_POST['user_id'];
$rank_arr = $_POST['rank'];
for($i = 0; $i < $total; $i++){
$user_id = $user_id_arr[$i];
$rank = $rank_arr[$i];
$query = "UPDATE users SET `rank`= '".$rank."' WHERE `user_id`= '".$user_id."'";
$MySQLi_CON->query($query);
header('Location: test7.php');
}
}
?>
When I press the UPDATE button, i get PHP Notice: Array to string conversion in....
It refers to line 30 which is this line:
$query = "UPDATE user SET rank=$_POST[rank][$row] WHERE user_id=$value ";
EDIT: Edited the code above to the working code. Thank you #Frayne Konok for your help.
You are very close.
The issue is that in this code $_POST[rank][$row] - rank is an undefined constant. You need it to be a string, like so $_POST['rank'][$row]. Also, pull the $POST variable out of the query directly to allow typecasting - you should always be very uncomfortable when you see a query that has $_POST data directly:
if(isset($_POST['update'])){
foreach ($result as $row => $value) {
// typecast to a number with decimals below. If you only need integers, than use (int)
$rank = (float)$_POST['rank'][$row];
$query = "UPDATE user SET rank={$rank} WHERE user_id={$value}";
$MySQLi_CON->query($query);
}
}
However, it would be better to use mysqli prepared statements rather than insert the variables directly - as it stand, the above code is vulnerable to SQL Injection attacks.
Your code should be modified to look something like so to prevent sql injection attacks:
if(isset($_POST['update'])) {
$stmt = $MySQLi_CON->prepare("UPDATE user SET rank= ? WHERE user_id= ?");
foreach ($result as $row => $value){
$stmt->bind_param('di', $_POST['rank'][$row], $value);
$stmt->execute();
}
$stmt->close();
}
You did a great mistake here, Why you use the $result in foreach
loop?? FRom where the $result comes?? The $result is the resource
of the sql query.
Try this:
if(isset($_POST['update'])){
$total = count($_POST['rank']);
$user_id_arr = $_POST['user_id'];
$rank_arr = $_POST['rank'];
for($i = 0; $i < $total; $i++){
$user_id = $user_id_arr[$i];
$rank = $rank_arr[$i];
$query = "UPDATE users SET `rank`= '".$rank."' WHERE `user_id`= '".$user_id."'";
$MySQLi_CON->query($query);
}
}
Try with this and let me know if there is any problem.

How to pass details from a SQL query to a details.php page

Very new to PHP so please go easy on me :)
I need to show the product details (manufacturer, tag number, etc) of a product if it's clicked by the user after being shown the results page. User types in a search form initially, then I get the catalogue_query.php to show the results, images, etc, that's all good. Each product has its own unique id which I thankfully get it to show in the url of the details.php page so I am doing something right.
However when I click on an item, even though I do get the "details.php" page shown with the correct id in the URL all it returns is the image and details for the very first item in the DB, not the actual item I clicked on - in other words the image and details do not match the id in the url.
Here is my code to show the results:
<?php
$query = $_POST ['query'];
$db = mysqli_connect ('localhost','root','root','asset_catalog');
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($db,"SELECT * FROM assets WHERE Description LIKE '%$query%' OR Manufacturer LIKE '%$query%' ORDER BY Description ");
echo "<table border='0'>
<tr>
</tr>";
while($row = mysqli_fetch_array($result))
{
if (($i % 5) == 0) echo "<tr>";
echo "<td><img src='".$row['Image']."' id='queryimg'><br>
<a href='details.php?ID=".$row['ID']."' style='color: #fff;'>{$row[Description]}</a></td>";
if (($i % 5) == 4) echo "</tr>";
$i++;
}
if ( $i > 0 && ($i-1) % 3 < 2) echo "</tr>";
echo "</table>";
?>
And here is my php for the details.php page:
<?php
$db = mysqli_connect ('localhost','root','root','asset_catalog');
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$ID = isset($_GET['ID']) ? (int) $_GET['ID'] : null;
$result = mysqli_query($db,"SELECT * FROM assets WHERE ID = $ID");
$row = mysqli_fetch_array($result);
echo "<table border='0'>
<tr>
</tr>";
echo "<tr>";
echo "<td><img src='".$row['Image']."' id='queryimg_details'>
<br>
{$row[Description]}</a>
<br>
{$row[Manufacturer]}
<br>
{$row[Tag_Num]}</td>";
echo "</tr>";
?>
Could anyone point me in the right direction? I am lost as to what I am doing wrong - or not doing.
Thanks a lot in advance!
$row can have multiple entries, so you should loop over it:
foreach($row as $r) {
// do stuff with this row like $r['Image']
}
You might want to change the variables names too.

Using PHP and mysql I want to allow a user to select result from array

I have a database of academic references which are part of a common bank which all users are able to see. I want to give the user the option to choose which one of the references they want to add to their own list and output on a separate page.
I aim to use a unique reference ID which is then linked to a separate user table and when they go to their personal page it outputs the references which they have chosen.
What I have tried to do so far is have a button next to all of the references which have been output and the button is linked to a form which then takes the user to a new page which performs the INSERT INTO statement to add the reference ID along side their student ID as a composite key.
What I have is as follows (removed a few fields to simplify):
$query = mysql_query("SELECT * FROM references")or die(mysql_error());
echo "<table>";
echo "<tr>";
echo "<td>Reference ID</td>";
echo "<td>Author</td>";
echo "<td>Save</td>";
echo "</tr>";
while($refer = mysql_fetch_array( $query ))
{
echo "<tr>";
echo "<td><form name='addreference' method='post' action='saveref.php'><input type='text' name='referenceid' readonly='readonly' id='refid' value='".$refer['refid'] . "'/></td> ";
echo "<td>".$refer['author'] . "</td> ";
echo "<td><center><input type='submit' name='addref' value='Add'></center></td>";
The correct Reference IDs output on this screen but when I do var_dump($_POST) on saveref.php the Reference ID posted is always that of the last one in the array regardless of which button is clicked on the list of references. What would be the best way to approach this?
Welcome to StackOverflow!
As noted in the comments, you should use mysqli instead of mysql, as mysql is deprecated.
Here's a rewrite to your form that will allow you to post an array of references to saveref.php. I included a lot of improvements, including double-quotes on your HTML attributes (a W3 recommendation), added thead and tbody to your table, and put your references in checkboxes with a single button at the bottom.
<form name="addreference" method="post" action="saveref.php">
<table>
<thead>
<tr>
<th>Reference ID</th>
<th>Author</th>
<th>Save</th>
</tr>
</thead>
<tbody>
<?php
$sql = "SELECT * FROM references";
$results = mysql_query($sql)
or die(mysql_error());
while ($refer = mysql_fetch_array($results)) {
echo <<<HTML
<tr>
<td>{$refer['refid']}</td>
<td>{$refer['author']}</td>
<td><input type="checkbox" name="references[]" value="{$refer['refid']}"/></td>
</tr>
HTML;
}
?>
<button type="submit" name="addref">Add Selected</button>
</form>
Your saveref.php file would then look like this:
<?php
$student_id = 1; // This value would get set elsewhere, I presume?
$references = !empty($_POST['references']) ? (array) $_POST['references'] : array();
$cnt = count($references);
if ($cnt) {
for ($i = 0; $i < $cnt; $i++) {
$references[$i] = "(" . ((int) $student_id) . ", " . ((int) $references[$i]) . ")";
}
$sql = "INSERT INTO references (student_id, reference_id) VALUES ";
$sql .= implode(", ", $references);
mysql_query($sql);
}

mysql database data into html table limiting column

My script is retrieving images from a database and displaying the images in a table. I want to have the table have 4 columns of images before it breaks the row and starts over. I've found some helpful answers on this forum but after re-organizing and fussing with the code it displays every image in it's own table rather than adding the row breaks after every fourth image. I'm running on little sleep, but hopefully a second pair of eyes could help me spot the problem.
<?php
include_once "connect.php";
$userid = $_SESSION['id'];
$albumid = $_GET['album'];
$pic = mysql_query("SELECT * FROM `pictures` WHERE userid='$userid' AND
albumid='$albumid'");
$i = 0;
echo "<center><table width='50%'><tr>";
while($row = mysql_fetch_assoc($pic)){
$id = $row["id"];
$thumbnail = $row["thumbnail"];
echo "<td><a href='viewphoto.php?photo=$id'><img src='$thumbnail'>
</a></td>";
if ($i && $i%4 == 0) echo '</tr><tr>';
$i++;
echo "</tr><tr>";
}
echo "</table> </center>";
?>
Fiddled around a little bit and
while($row = mysql_fetch_assoc($pic)){
$id = $row["id"];
$thumbnail = $row["thumbnail"];
if ($i && $i%4 == 0) echo '</tr><tr>';
$i++;
echo "<td><a href='viewphoto.php?photo=$id' rel='facebox'><img src='$thumbnail'>
</a></td>";}
worked like a charm.
The problem is that you are declaring your table inside the while loop. You should open and close your table tags on either side of the while loop, and only have tr and td's inside the loop.
There seem to be a couple of interchanged variable names here too that would cause unexpected behaviour. In your SQL query I think you mean ...albumid='$albumid'... and in the while loop I think you want while($row = mysql_fetch_assoc($pic)) {
Also, you should take note that this SQL query is open to SQL injection attacks
$i was initialized inside the loop. and Table also bring outside.
see the code below.
<?php
include_once "connect.php";
$userid = $_SESSION['id'];
$albumid = $_GET['album'];
$pic = mysql_query("SELECT * FROM `pictures` WHERE userid='$userid' AND
albumid='$pic'");
$i = 0;
echo "
<center><table width='50%'><tr>";
while($row = mysql_fetch_assoc($image)){
$id = $row["id"];
$thumb = $row["thumb"];
$date = strftime("%b %d, %Y", strtotime($row['date']));
echo "<td><img src='$thumbnail'></td>";
if ($i && $i%4 == 0) echo '</tr><tr>';
$i++;
}
echo "</table> </center>";
?>

Categories