How to delete from my database in PHP/mysql? - php

Hi there I have many implementations of some php files. All of which have some errors. I will start off with an apology as this is my first question on here and I am certain that I will do this incorrectly as I see many first timers do. I will give as much info as possible and make it relevant to as many people as possible.
I have a database and am having trouble deleting from it. The database is simple. It includes resource_id name room description time_available and uer_id.
Although I expect it to output name description and resources_id it only outputs name and description and it will not let me delete name by resources_id.
How to delete from my database in PHP/mysql?
This is my delete_resources.php
{
<html>
<head>
<title>Delete a Record from MySQL Database</title>
</head>
<body>
<?php
$db_host = "#######";
// Place the username for the MySQL database here
$db_username = "#######";
// Place the password for the MySQL database here
$db_pass = "#######";
// Place the name for the MySQL database here
$db_name = "#######";
//
$con = mysqli_connect("$db_host","$db_username","$db_pass","$db_name");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
mysqli_close($con);
}
$result = mysqli_query($con, "SELECT * FROM resources");
echo 'name' . "\t" . 'description' . "\t" . 'resources_id';
echo "<br>";
while($row = mysqli_fetch_array($result))
{
echo $row['name'] . "\t" . $row['description'] . "\t" . $row['resources_id'];
echo "<br>";
}
// Echoes: string
echo gettype($array);
//
if(isset($_POST['delete']))
{
// Query to select an int column
$resources_id = $_POST['resources_id'];
$sql = "DELETE name From resources ".
"WHERE resources_id = $resources_id" ;
//mysql_select_db('b32_13993766_csc411');
//$retval = mysql_query( $sql, $conn );
if(! $result )
{
die('Could not delete data: ' . mysql_error());
}
else if( $result )
{
echo "Deleted data successfully\n";
}
//mysql_close($conn);
}
else
{
?>
<form method="post" action="<?php $_PHP_SELF ?>">
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<td width="100">Resource ID</td>
<td><input name="resources_id" type="text" id="resources_id"></td>
</tr>
<tr>
<td width="100"> </td>
<td> </td>
</tr>
<tr>
<td width="100"> </td>
<td>
<input name="delete" type="submit" id="delete" value="Delete">
</td>
</tr>
</table>
</form>
<?php
}
?>
</body>
</html>
//
}

You are not executing that delete query. Should look like
$recources_id=intval($resources_id);
$sql = "DELETE FROM resources WHERE resources_id = $resources_id" ;
$result = mysqli_query($con, $sql); // This is missing

$sql_query="Delete from your_table_name where id ='".$your_id."'";

$sql = "DELETE FROM resources WHERE resources_id = $resources_id" ;

Your $result is not relevant at all with your delete query (it is referring to the $result above, not the one with the delete). Try changing to this and see if it works.
if(isset($_POST['delete']))
{
// Query to select an int column
$resources_id = $_POST['resources_id'];
$sql = "DELETE name From resources ".
"WHERE resources_id = $resources_id" ;
$result = mysqli_query($con, $sql); //add this line
//mysql_select_db('b32_13993766_csc411');
//$retval = mysql_query( $sql, $conn );
if(! $result )
{
die('Could not delete data: ' . mysql_error());
}
else if( $result )
{
echo "Deleted data successfully\n";
}
//mysql_close($conn);
}

Related

updating database update

I am having trouble getting the database to update. Is there something wrong with my sql update statement? I checked the sql statement and it says that there were no records in the database. I am not sure what to do.
<!-- template for mySql database access. -->
<!DOCTYPE html>
<html>
<head>
<title>CRUD</title>
<link href="/sandvig/mis314/assignments/style.css" rel="stylesheet" type="text/css">
</head>
<div class="pageContainer centerText">
<h3>CRUD (Create, Read, Update, & Delete) Database</h3>
<?php
//include database connection
include("DatabaseConnection2.php");
//connect to database
$link = fConnectToDatabase();
//Retrieve parameters from querystring and sanitize
$nameF = fCleanString($link, $_GET['nameF'], 15);
$nameL = fCleanString($link, $_GET['nameL'], 15);
$deleteID = fCleanNumber($_GET['deleteID']);
$updateID = fCleanNumber($_GET['updateID']);
$updateID2 = fCleanNumber($_GET['updateID2']);
//Populate Textbox
if (!empty($updateID)) {
$sql = "SELECT NameL, NameF
FROM customertbl
WHERE custID = '$updateID'";
mysqli_query($link, $sql) or die('Delete error: ' . mysqli_error($link));
$result = mysqli_query($link, $sql)
or die('SQL syntax error: ' . mysqli_error($link));
$row = mysqli_fetch_array($result);
$strFName2 = $row[NameF];
$strLName2= $row[NameL];
}
?>
<hr>
<form class="formLayout">
<div class="formGroup">
<label>First name:</label>
<input name="nameF" type="text" autofocus value="<? echo $strFName2; ?>">
</div>
<div class="formGroup">
<label>Last name:</label>
<input name="nameL" type="text" value="<? echo $strLName2; ?>">
</div>
<div class="formGroup">
<label> </label>
<button>Submit</button>
<input type="hidden" name="updateID2" value="<? echo $updateID; ?>">
</div>
</form>
<?php
//Update
if (!empty($updateID2))
{
$sql = "UPDATE customertbl
SET NameL = '$strFName2', NameF ='$strLName2'
WHERE custID = '$updateID2' ";
mysqli_query($link, $sql) or die('Insert error: ' . mysqli_error($link));
}
//Insert
if (!empty($nameF) && !empty($nameL)) {
$sql = "Insert into customertbl (NameL, NameF)
VALUES ('$nameL', '$nameF')";
mysqli_query($link, $sql) or die('Insert error: ' . mysqli_error($link));
}
//Delete
if (!empty($deleteID)) {
$sql = "Delete from customertbl WHERE CustID= '$deleteID' ";
mysqli_query($link, $sql) or die('Delete error: ' . mysqli_error($link));
}
//List records
$sql = 'SELECT custID, NameF, NameL
FROM customertbl order by custID';
//$result is an array containing query results
$result = mysqli_query($link, $sql)
or die('SQL syntax error: ' . mysqli_error($link));
echo "<p>" . mysqli_num_rows($result) . " records in the database</p>";
?>
<table class="simpleTable">
<tr>
<th>Cust. ID</th>
<th>F. Name</th>
<th>L. Name</th>
<th>Delete</th>
<th>Update</th>
</tr>
<?php
// iterate through the retrieved records
while ($row = mysqli_fetch_array($result)) {
//Field names are case sensitive and must match
//the case used in sql statement
$custID = $row['custID'];
echo "<tr>
<td>$custID</td>
<td>$row[NameF]</td>
<td>$row[NameL]</td>
<td><a href='?deleteID=$custID'>Delete</a></td>
<td><a href='?updateID=$custID'>Update</a></td>
</tr>";
}
?>
</table>
</div>
</body>
</html>
The offending code block
//Update
if (!empty($updateID2))
{
$sql = "UPDATE customertbl
SET NameL = '$strFName2', NameF ='$strLName2'
WHERE custID = '$updateID2' ";
mysqli_query($link, $sql) or die('Insert error: ' . mysqli_error($link));
}
makes references to variables $strFName2 and $strLName2 which are variables that are only populated conditionally.
//Populate Textbox
if (!empty($updateID)) {
$sql = "SELECT NameL, NameF
FROM customertbl
WHERE custID = '$updateID'";
mysqli_query($link, $sql) or die('Delete error: ' . mysqli_error($link));
$result = mysqli_query($link, $sql)
or die('SQL syntax error: ' . mysqli_error($link));
$row = mysqli_fetch_array($result);
$strFName2 = $row[NameF];
$strLName2= $row[NameL];
}
Since the variables $strFName2 and $strLName2 are undefined during the UPDATE SQL query, you're not seeing the desired results.
The query should reference $nameF and $nameL since those variables are always defined (not contained within a conditional) and the form inputs use nameF and nameL in their name attributes.
$sql = "UPDATE customertbl
SET NameL = '$nameF', NameF ='$nameL'
WHERE custID = '$updateID2';";
You also need to fix your DELETE query to reference the column custID and not CustID as it appears your schema uses the former.
$sql = "Delete from customertbl WHERE custID= '$deleteID' ";

if mysql any field is empty then show a word like null

I need to know that, if there is any empty field then display null in retrieve form. i mean,
name----------age----------country
xyz----------" "---------usa
so, the form will show
name: xyz
age: show null
country: usa
<?php
$dbhost = '';
$dbuser = '';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$No=$_GET['No'];
$sql = "SELECT * from tablename where Name='$Name'";
mysql_select_db('dbname');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
?>
<table width="100%"><tr><td>
<table>
<tr>
<tr><td class="a" style="width:20%">Name</td><td style="width:20%" class="a"><a class="res" ><?php echo $row['Name'];?></a></td></tr>
<tr><td class="a" style="width:20%">age</td><td style="width:20%" class="a"><a class="res"><?php echo $row['age'];?></a></td></tr>
<tr><td class="a" style="width:20%">country</td><td style="width:20%" class="a"><a class="res"><?php echo $row['country'];?></a></td></tr>
</tr>
</table>
<?php
}
mysql_close($conn);
?>`
Just test if the result is empty and if it is show Null.
<?php if ($row['Name'] != '') {
echo $row['Name'];
} else {
echo "Null";
}?>
echo empty($row['age']) ? 'null' : $row['age']
PS: avoid SQL Injection!

Why this is not updating Information

Why this code is not update information?
HTML Form:
<form>
<lable> ID# :</lable>
<input id= "ID" name= "ID" type= "text">
<p>
<label>Select field to Edit</label>
<select name="change">
<option value=""></option>
<option value="fname">First Name</option>
<option value="lname">Last Name</option>
<option value="email">Email</option>
<option value="city">City</option>
<option value="zip">Zip</option>
</select>
<lable> Enter the value to be replaced </label>
<input id = "replace" name = "replace" type = "text">
</p>
<input name="submit" type="submit" value="Submit">
PHP Code for updating information from database:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$conn = mysql_connect($servername,$username,$password);
if(!$conn)
{
die('Error!' . mysqli_error());
}
$sql = 'SELECT * FROM users';
mysql_select_db('mitsdatabase');
$retval = mysql_query($sql, $conn);
if(! $retval)
{
die('Could not get data:' . mysql_error());
}
echo "<table width='300' cellpadding='5' border='1'>";
echo "<tr> <td>ID#</td> <td>FirstName</td> <td>LastName</td> <td> Email </td> <td> City </td> <td> State </td> <td> Zip </td> </tr>";
while($row = mysql_fetch_array($retval,MYSQL_ASSOC))
{
echo "<tr> <td>{$row['ID']}</td> . <td>{$row['fname']}</td> . <td>{$row['lname']}</td> . <td>{$row['email']}</td> . <td>{$row['city']}</td> . <td>{$row['state']} </td>. <td>{$row['zip']}</td>";
}
echo "</table>";
$db_id = $_POST['ID'];
$db_select = $_POST['change'];
$db_replace= $_POST['replace'];
echo " Do you want to edit any entry?";
if(!_POST['submit'])
{
echo " ";
}
else{
mysqli_query("UPDATE users SET db_select='$db_replace' WHERE ID = $db_id ");
}
mysql_close($conn);
?>
I want to update informate selected from select field but somehow it is not doing any thing. Can someone help me what is wrong with this code.
Is your PHP on the same page as your HTML? If not, you are not directing to your php code within the <form> element in your HTML.
For example, if your PHP file was called 'myphpcode.php' (and in the same folder as your HTML code) then you could direct to it using the following:
<form method="post" action="myphpcode.php">
If you want to post to the same page just change <form> to <form method="post" action="#"> and get variables in php like this $nameofvar = $_POST['nameofinputfield'] . Each input field should have the name tag.
Also try to change your mysql connect to this :
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
and after you finished the query
$conn->close();
and the query to insert
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
and you can modify this $sql string to update or delete

fetch data from array is very slow while display

This is my code:
<?php
if(isset($_POST['submit']) & !empty($_POST['appid'])) {
$app = mysql_real_escape_string($_POST['appid']);
//database parameters
$conp = mysqli_connect($hostname, $user, $password, $database) or die('error in connection' . mysqli_error());
//actual data for appid's
$appsi = mysqli_query($conp, "SELECT distinct package_name FROM `user_app` where `app_id` = '$app'");
$all = array();
while($row = mysqli_fetch_assoc($appsi)) {
$all[] = $row["package_name"]; // array problem
}
foreach ($all as $value) {
$install = mysqli_query($conp, "SELECT COUNT(*) AS installs from `install` where package_name = '$value'");
$row = mysqli_fetch_assoc($install);
$data[] = '<b>' .$row["installs"] . '</b>';
$reg = mysqli_query($conp, "SELECT COUNT( DISTINCT `imei_num` ) AS reg FROM `user_app` WHERE package_name = '$value'");
$row = mysqli_fetch_assoc($reg);
$regd[] = '<b>' .$row["reg"] . '</b>';
}
}
mysqli_close($conp);
?>
<html>
<head>
<title>script</title>
</style>
</head>
<body>
<span style="text-align: center"><h1>Beta</h1></span>
<form name="query" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<p>Enter Application-Specific Id:</p>
<select name='appid'>
<?php
$conp = mysqli_connect($hostname, $user, $password, $database) or die('error in connection' . mysqli_error());
$getid = mysqli_query($conp, "SELECT distinct `app_id`, `appidt` from `user_app` group by `app_id`") or die('get data failed' . mysqli_error());
while(($row = mysqli_fetch_assoc($getid)) != null) {
echo "<option value = '{$row['app_id']}' selected = 'selected'";
if ($selected == $row['app_id']) {
echo "selected = 'selected'";
}
echo ">{$row['appidt']}</option>";
}
mysqli_close($conp);
?>
</select>
<p><input type="submit" name="submit" value="Go" /></p>
</form>
<div>
<p><?php echo '<br />' .'<b>'. 'Application Id : '. $app . '</b>'; ?> </p>
<hr />
<table border=2px width=100%>
<tr>
<th><b>App Packages</b></th>
<th><b>Registrations</b></th>
<th><b>Installs</b></th>
</tr>
<tr>
<td><?php echo implode("<br><br>", $all); ?></td>
<td align="center"><?php echo implode("<br><br>", $regd); ?></td>
<td align="center"><?php echo implode("<br><br>", $data); ?></td>
</tr>
</table>
<p><?php echo "$name"; ?></p>
</div>
</body>
</html>
I am fetching my all package names in an array: all[], packages might be 10 or 20 in ranges, after this i want all downloads corresponding to packages which is on another table name downloads and packages on another table app_packages.
I can't uses join because package table contain specific packages but downloads contain many number of downloads corresponding to packages.
So, i put all packages in all[] and use them in foreach loop name $value, now i get all installs per packages and i can display it via implode function. But in my frontend, when i select an appid from dropdown as you can see, it will take huge time to retrieve downloads number per packages. This is not what i want to display because it is very time taking.
Please see this problem, and if i missing something in explanation then i apologize, prompt me and i mention it.
Using query in loop is a bad idea. that is the reason you are geting slow result. it touches database on each iteration. you can do this with subquery or join as alternative way.

Deleting Multiple Records using Checkboxes in PHP

I am having an issue where I need to be able to delete multiple records using checkboxes.
Here is the code that I currently have.
<?php
$host = "localhost";
$user = "root";
$pass = "";
$dbName = "ticket_history";
$table_name = "ticket_history";
################ Connect to the Database and SELECT DATA ####################################
$conn = mysql_connect($host, $user, $pass) or die ("Unable to connect");
mysql_select_db($dbName);
$query = "SELECT Date,Ticket_Number,Description,Result FROM $table_name";
$result = mysql_query($query);
$count=mysql_num_rows($result);
#############################################################################################
?>
<HTML>
<HEAD>
<TITLE></TITLE>
</HEAD>
<BODY>
<table width=50%>
<form method="post" action="insert_ticket.php">
<table width border='0'>
<tr><td> Date:<input type="text" name="date"/></td>
<td>Ticket #:<input type="text" name="ticket"/></td></tr>
<table>
<tr><td>Description:<TEXTAREA COLS=50 name="description"></TEXTAREA></td></tr>
<tr><td> Result :<TEXTAREA COLS=50 name="result"></TEXTAREA></td></tr>
<tr><td><input type="submit" name="submit" value="Add"/></td></tr>
</table>
</table>
</form>
<form method="post" action="delete_ticket.php">
<input type="submit" name="delete" value="Delete"/>
</form>
</table>
<?php
print "<table width=80% border=1>\n";
$cols = 0;
while ($get_info = mysql_fetch_assoc($result)){
$id = $get_info->id;
if($cols == 0)
{
$cols = 1;
print "<tr>";
print "<th>Select</th>";
foreach($get_info as $col => $value)
{
print "<th>$col</th>";
}
print "<tr>\n";
}
print "<tr>\n";
print "<td><input type='checkbox' name='selected[]' id='checkbox[]' value=$id></td>";
foreach ($get_info as $field)
print "\t<td align='center'><font face=arial size=1/>$field</font></td>\n";
print "</tr>\n";
}
print "</table>\n";
mysql_close();
?>
<!------------------------------------------------------------!>
</BODY>
</HTML>
Delete.php
<?php
$host = "localhost";
$user = "root";
$pass = "";
$dbName = "ticket_history";
$table_name = "ticket_history";
################ Connect to the Database and SELECT DATA ####################################
$conn = mysql_connect($host, $user, $pass) or die ("Unable to connect");
mysql_select_db($dbName);
$query = "SELECT Date,Ticket_Number,Description,Result FROM $table_name";
$result = mysql_query($query);
$count=mysql_num_rows($result);
#####################################
if($_POST['delete']) {
$checkbox = $_POST['selected'];
$countCheck = count($_POST['selected']);
for($i=0;$i<$countCheck;$i++) {
$del_id = $checkbox[$i];
$sql = "DELETE FROM ticket_history WHERE Auto = $del_id";
$result = mysql_query($sql);
}
}
?>
I just want to be able to delete rows checked. How would I go about doing this effectively and efficiently?
Thank you in advance.
The simple answer to your question would be to use:
$sql = sprintf('DELETE FROM ticket_history WHERE Auto IN ()',
implode(',', $checkbox));
However as people will jump in and tell you, you are vulnerable to SQL injection. You should never trust user input. You are deleting using an ID, which I'm assuming must be an integer.
Using something like this will validate that:
$ids = array();
foreach($_POST['selected'] as $selected) {
if (ctype_digit($selected)) {
$ids[] = $selected;
}
else {
// If one is invalid, I would assume nothing can be trusted
// Depends how you want to handle the error.
die('Invalid input');
}
}
$sql = sprintf('DELETE FROM ticket_history WHERE Auto IN (%s)',
implode(',', $ids));
Other issues:
You seem to be using id's, but have not selected that field in your initial query.
$query = "SELECT Date,Ticket_Number,Description,Result FROM $table_name";
Then you reference:
$id = $get_info->id;
Check the HTML output is actually what you expect.
In your delete query, you are referencing the field Auto. Is that your ID field?
And lastly, there no checking if the user has permission to do so. If this is a public site anyone can delete from that table.
Example of using two submit buttons within one form:
<?php
if (isset($_POST['create'])) {
echo "Create!";
}
elseif (isset($_POST['delete'])) {
echo "Delete!";
}
?>
<html>
<form method="post">
<input type="submit" name="create" value="Create"/>
<input type="submit" name="delete" value="Delete"/>
</form>
</html>

Categories