how to delete single row using php - php

Dear please help me
i am getting some error in my code
this is my view.php page
<html>
<body>
<table style="border:#333 solid" border="2">
<tr>
<td>ID:</td>
<td>NAME:</td>
<td>EMAIL:</td>
<td>MOBILE:</td>
<td>EDIT:</td>
<td>DELETE:</td>
</tr>
<?php
include_once('connect.php');
$query="select * from emp";
$conn=mysqli_query($con,$query);
if(isset($conn))
{
echo"This is all data of table.";
}
else
{
die("query is not execute". mysqli_error());
}
while($row=mysqli_fetch_array($conn))
{
?>
<tr>
<td><?php echo $row['emp_id']; ?></td>
<td><?php echo $row['emp_name']; ?></td>
<td><?php echo $row['emp_address'] ?></td>
<td><?php echo $row['emp_salary'] ?></td>
<td><font color="#FF0000">EDIT</font></td>
<td><font color="#FF0000">DELETE</font></td>
</tr>
<?PHP
}
?>
</table>
</body>
</html>
and this is my delete.php file:
<?php
include_once('connect.php');
$id=$_GET['emp_id'];
$query="delete from emp where emp_id='$id'";
$del=mysqli_query($con,$query);
if($del)
{
echo"record has been deleted";
}
else
{
die("Record is not deleted it is query error.".mysqli_error());
}
?>
How can I access the ID of the view.php in the delete.php file and how to delete a single row in my db table.
I don't understand how to access the id of view.php.
In this program I don't delete the selected row. Please tell me how to delele data.
please anyone help me.

You are sending edit.php?id= so need to get id from query string using GET['id']
$id = $_GET['id'];

change the code in delete.php as follow
<?php
include_once('connect.php');
$id=$_GET['id'];
$query="delete from emp where emp_id='$id'";
$del=mysqli_query($con,$query);
if($del)
{
echo"record has been deleted";
}
else
{
die("Record is not deleted it is query error.".mysqli_error());
}
?>

Please also realize that using $_GET data within your queries is only asking for trouble, especially when it's not escaped properly. You're opening your self up to SQL injection attacks.
Make use of mysql_real_escape_string if you're going to be using mysql_* functions, just realize that it has been deprecated in PHP 5.5.
You also have the option of using MySQLi or PDO would be preferable since they both make use of prepared statements as mentioned in this previous question How can I prevent SQL-injection in PHP?

Related

Unable to produce SQL query in PHP/HTML

I'm having some trouble generating output from an sql query via php. When I execute the query "SELECT * from projectdb WHERE name = 'Crys' or ID = 14142" on phpmyadmin it returns valid results, but attempting to do so by passing a post value yields an empty table. See code below:
<html>
<title>Search result</title>
<body>
<table border="1px">
<tr>
<td>name</td>
<td>ID</td>
<td>position</td>
<td>job scope</td>
<td>contact_no</td>
<td>days_off</td>
<td>wages</td>
</tr>
<?php
if (isset($_POST['value']))
{
$ID=$_POST['staff ID'];
$name=$_POST['staff name'];
$admincon =mysqli_connect("localhost","root","","projectdb");
/* Query I need to execute and print in table*/
$sqlsrch2 =mysqli_query($admincon, "select * from staff where name='".$name."' or ID='".$ID."'");
while($result=mysqli_fetch_assoc($sqlsrch2)){
?>
/* table where results needs to be printed */
<tr>
<td><?php echo $result['name'];?></td>
<td><?php echo $result['ID'];?></td>
<td><?php echo $result['position'];?></td>
<td><?php echo $result['job_scope'];?></td>
<td><?php echo $result['contact_no'];?></td>
<td><?php echo $result['days_off'];?></td>
<td><?php echo $result['wages'];?></td>
</tr>
<?php
}
}
?>
</table>
</body>
</html>
A few points to note:
I'm just a beginner in PHP and SQL; I'm just looking for a simple answer.
Security is not at all a concern here; this is just a rough demo.
If this is marked as duplicate, do help redirect me to a link where I can get the solution. Thanks!

I want to display the message “no result found” when the query returns no result

I am using the following code to search in the site..I wish to display the message "no result found" when the query returns no result.What changings should i do in the code
My Code:
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
if(isset($_REQUEST["submit"]))
{
$user = $_REQUEST["user"];
mysql_connect("localhost","root","");
mysql_select_db("iata");
$query=mysql_query("SELECT * FROM code WHERE airportcode LIKE '$user'");
$rowcount=mysql_num_rows($query);
?>
<table border="1" align="center">
<tr>
<td>City Name</td>
<td>3 Letter City Code</td>
<td>Airport Name</td>
<td>3 Letter Airport Code</td>
</tr>
<?php
for($i=1;$i<=$rowcount;$i++)
{
$row = mysql_fetch_array($query);
?>
<tr>
<td><?php echo $row["cityname"] ?></td>
<td><?php echo $row["citycode"] ?></td>
<td><?php echo $row["airportname"] ?></td>
<td><?php echo $row["airportcode"] ?></td>
</tr>
<?php
}
}
?>
</table>
<form method="POST">
<input type="text" name="user">
<input type="submit" name="submit" value="Submit">
</form>
You already uses the rowcount. Just check if the count is equal to 0 and you'll know if you have results or not.
More importantly, you are using mysql_* functions. It's advised to use mysqli_* functions instead for almost a decade, they are deprecated since PHP5.5 and have been removed since PHP7.0.
You should use mysqli_* function, or even better PDO :
try {
$db = new PDO('mysql:host=localhost;dbname=iata', 'root, '');
$stmt = $db->prepare("SELECT * FROM code WHERE airportcode LIKE ?");
$stmt->execute(array($user));
while ($row = $stmt->fetch()) {
// Your code here
}
$db = null;
} catch (PDOException $e) {
print "Error !: " . $e->getMessage() . "<br/>";
die();
}
Don't touch code with mysql_* functions in it, don't write it, don't copy it, don't give it to anyone, don't even poke it with a stick ! These functions are vulnerable and would render as vulnerable any application that relies on them !
Do this
if ($rowcount == 0) {
$message = "No Result";
}
Now you can echo $message anywhere on the page to display the message.
Add the following to your code where you want the message to appear:
if ($rowcount == 0) {
echo 'result set is = 0';
}

Code to delete table row in database won't work

I'm trying to delete a row in a table in my database, but it isn't working... The connection works. I've echoed the table row id to ensure it is working and still it won't delete...
Let me know if you need the connection code too.
code:
<table>
<tr>
<td>Recent Posts</td>
</tr>
<?php while($row = mysql_fetch_array($result)) : ?>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['phone number']; ?></td>
<td>Schedule</td>
</tr>
<?php endwhile; ?>
</table>
delete.php code:
<?php
$b=$_GET['id'];
$sql='DELETE FROM on call WHERE id=$b';
//echoing just to make sure it is working correctly...
echo $b;
?>
</br>
</br>
<a href='index2.php'>back to list</a>
You didn't execute your DELETE sql command using mysql_query
$sql = "DELETE FROM ...";
mysql_query($sql);
Please note that the mysql functions are now deprecated. Also, you should protect your code against SQL injections.
I don't understand your sql syntax. if 'on call' is your table, please rename your table to on_call and so your sql should :
$sql = "DELETE FROM on_call WHERE id = '" . $b . "'";
You did not execute your sql.
mysql_query($sql); use mysql function to prevent injection.

Displaying mySQL row in an HTML table without having to specify each column individually

I'm creating a form where users can view and edit their account information and I'd like to streamline this as much as possible since there are a lot of form fields. I've selected all the customer's data without specifying the column names, but I'm having trouble displaying in the correct place in an HTML table without having to call each one individually.
I've used mysql_fetch_array in the code below, but it would be quite cumbersome to do for 300+ fields. I know that mysql_fetch_assoc can be used, but I haven't figured out how to then print in the correct place.
mysql_fetch_assoc (Pardon my ignorance, but I couldn't get this to work without using WHILE and FOREACH)
while ($row = mysql_fetch_assoc($result)) {
foreach($row as $key=>$value){
echo "$key: $value<br />\n ";
}}
This works but requires specifying each field individually
<?php
//Database connection and Open database
require_once('config.php');
$result = mysql_query("SELECT customer_info.*, style.* FROM customer_info, style WHERE customer_info.user_id = style.user_id AND customer_info.user_id=$user_id ") or die(mysql_error());
$row = mysql_fetch_array($result );
?>
<table border="0" cellspacing="2" cellpadding="2">
<tr><td name="fname">First Name: <?php echo $row['fname']; ?></td>
<td name="lname">Last Name: <?php echo $row['lname']; ?></td>
<td name="email">Email: <?php echo $row['email']; ?></td>
<td name="colors_love">Colors Love: <?php echo $row['colors_love']; ?></td>
</tr></table>
Is there a way to essentially reverse the way I achieve this with my INSERT INTO code? if so, I'm assuming that will simplify my next task (allowing users to edit their information)
$fieldlist=$vallist='';
foreach ($_POST as $key => $value) {
$fieldlist.=$key.',';
$vallist.='\''.($value).'\',';
}
$result = mysql_query('INSERT INTO taste ('.$fieldlist.') VALUES ('.$vallist.')');
Leaving out the fact that using the mysql library is a terrible idea, you're actually most of the way there:
<table>
<?php while ($row = mysql_fetch_assoc($result)): ?>
<tr>
<?php foreach($row as $key=>$value) {
echo "<td>$key: $value</td>\n ";
} ?>
</tr>
<?php endwhile; ?>
</table>
You obviously would want to clean this up for a real form, since echoing db field names isn't exactly user-friendly.
kind of this?
<?php
//Database connection and Open database
require_once('config.php');
$result = mysql_query("SELECT customer_info.*, style.* FROM customer_info, style WHERE customer_info.user_id = style.user_id AND customer_info.user_id=$user_id ") or die(mysql_error());
$row = mysql_fetch_assoc($result );
?>
<table border="0" cellspacing="2" cellpadding="2">
<tr><?php foreach($row as $field => $content): ?>
<td><?php echo $field; ?>: <?php echo $content; ?></td>
<?php endforeach; ?></tr>
</table>

Use output from MySQL to extract additional info

How can I use the output of a MySQL query as to extract extra info from the database about that output?
For example, if my query generates a list of names and there is extra info about each name existing in the database, when I click on the name on the output page, the system will extract the relevant info from the database and show it on another page.
EDIT: Here's the code:
<?php
// you can delete mysql-assoc
while($row = mysql_fetch_array($rs, MYSQL_ASSOC)) {
?>
<tr align="center">
<td width="5%">
<a href="// I don't know what do put here " >
<?php print("{$row["pid"]}");?>
</a>
</td>
<td><?php print("{$row["place"]}");?></td>
<td><?php print("{$row["date"]}");?></td>
<td><?php print("{$row["ppp"]}");?></td>
<td><input type="button" value="Book"></td>
</tr> <?php } ?>
Set each row of the first output results equal to a variable, and then have an if statement in php that looks for strings in those variables, and then (upon some sort of a page refresh button since php is server-side code) displays the additional content.
Great; here's what you're missing:
<a href="<?php // I don't know what to put here ?>" >
Should be:
<a href="<?php echo 'database.php?action=viewrecord({$row["pid"]})'?>" >
From there, you should be able to extract the relevant info using the pid of the user.
On a side note, unless you're really worried about spacing, you should just dump out the relevant HTML; doing so will save you the task of repeatedly typing <?php ?> every time you want to dump out a variable.
<?php
// you can delete mysql-assoc
while($row = mysql_fetch_array($rs, MYSQL_ASSOC)) {
echo "<tr align='center'>";
echo "<td width='5%'>";
echo "<a href='database.php?action=viewrecord({$row['pid']})'>";
echo "{$row['pid']}";
echo "</a>";
echo "</td>";
echo "<td>{$row['place']}</td>";
echo "<td>{$row['date']}</td>";
echo "<td>{$row['ppp']}</td>";
echo "<td><input type='button' value='Book'></td>";
echo "</tr>";
}
?>
Thanks for the help but this doesn't work :( I'm beginner in php when I press the record the url looks like localhost/ass/database.php?action=viewrecord%28{$row[
This isnt a direct answer to your question perse but since youre new to php im goign to through it out there. The syntax you uisng makes unicorns cry. It give me a headache jsut tryign to decipher it. Heres the same code in an alternative way:
<?php while($row = mysql_fetch_array($rs, MYSQL_ASSOC)): ?>
<tr align="center">
<td><?php printf('%s', url_encode('viewrecord('.$row['pid'].')'), $row['pid']); ?></td>
<td><?php echo $row['place']; ?></td>
<td><?php echo $row['date']; ?></td>
<td><?php echo $row['ppp']; ?></td>
<td><input type="button" value="Book"></td>
</tr>
<?php endwhile; ?>
However this database.php?action=viewrecord() worries me. I hope youre not using eval to execute a function passed by URL. Typically this would look something more like: database.php?action=viewrecord&id=2. You would verify that the action parameter is valid, and then invoke a function tied to that parameter which may or may not be the actual function name, and you would pass in the id parameter.
Eaxample database.php:
$action = isset($_POST['action']) ? $_POST['action'] : 'index';
switch($action) {
case 'viewrecord':
if(isset($_POST['id']) {
viewrecord((integer) $_POST['id']);
}
break;
// a whole bunch of other cases here for other actions
default:
// the default thing to do if an action is in valid
}
// the rest of your processing

Categories