So I am trying to get a row of information to delete from my database 'barcode' but it is not happening. I hit the submit button but it does not delete the 'itemcode' that I have typed in the input box. HELP??
following edit i have a new error
Error:You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1' at line 1
Delete.php
Testing to see if items deleted
<form action="delete.php" method="post">
<tr>
<td>Item Code: </td>
<td><input type="text" name="itemcode" autofocus></td>
<td><input type="submit" value="Delete"></td>
</tr>
</table> <br>
<?php
require_once('dbconnect.php');
$txtitemcode = (!empty($_POST['itemcode']) ? $_POST['itemcode'] : null);
$result = mysqli_query($con, "SELECT * from barcode order by itemcode");
$delete = mysqli_query($con,"DELETE FROM barcode WHERE itemcode='itemcode'");
if(!mysqli_query($con, $delete))
{
echo('Error:'.mysqli_error($con));
}
echo "<center><table border=1>";
echo"<tr>
<th>ITEM CODE:</th>
<th>Company Shipping:</th>
</tr>";
while($row = mysqli_fetch_array ($result))
{
echo"<tr>
<td align= center>".$row['itemcode']."</td>
<td align=center>".$row['item']."</td>
</tr>";
}
echo "</table>";
mysqli_close($con);
dbconnect.php
$con = mysqli_connect("localhost","root","root","db1");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
echo "Connected to Database. Please Continue.";
}
Add.php The add.php works but delete does not.
php
include('dbconnect.php');
function get_posts() {
global $con;
$txtitemcode = (!empty($_POST['itemcode']) ? $_POST['itemcode'] : null);
$txtitem = (!empty($_POST['item']) ? $_POST['item'] : null);
$sql1 = "INSERT INTO barcode (itemcode, item) VALUES ('".$txtitemcode."','".$txtitem."')";
if(!mysqli_query($con, $sql1))
{
die('Error:'.mysqli_error());
}
echo "<script> alert('1 record added');
window.location.href='index.php';
</script>";
}
get_posts(); //Must have to show posts in table
mysqli_close($con);
?
You are executing the stuff twice:
This line executes the query and puts the result in to $delete:
$delete = mysqli_query($con,"DELETE FROM barcode WHERE itemcode='itemcode'");
Now you are issuing another query with the result from above:
if(!mysqli_query($con, $delete))
{
echo('Error:'.mysqli_error($con));
}
And this is issuing an error as posted: the result in $delete is "1" and "1" isn't a statement.
Change:
$delete = mysqli_query($con,"DELETE FROM barcode WHERE itemcode='itemcode'");
if(!$delete) // or if ( $delete === false )
{
echo('Error:'.mysqli_error($con));
}
Furthermore, following the logic of these few lines, I assume it should be:
if ( isset($txtitemcode) )
{
$delete = mysqli_query($con,"DELETE FROM barcode WHERE itemcode='" . $txtitemcode . "'");
if(!$delete) // or if ( $delete === false )
{
echo('Error:'.mysqli_error($con));
}
}
Related
I've spent a lot of time messing around with PHP and MYSQL and I've finally managed to create a "to do list" sort of thing that allows the user to submit a "to do" task and for it to add it to a database and then show it. I've followed many tutorials as I've tried to teach myself PHP blah blah. But for some reason i cannot get the delete script working.
echo "<td><a href='delete.php?=Delete" . $row['task_id']."'>Delete"."</a>"."</td></tr>" . "$record->ID";
Above is the code for the delete button
Here is the delete script apologies for the many commented out lines I've tried many 'solutions'.
$ID = $_GET['task_id'];
//$delete_query = "DELETE FROM Tasks WHERE ID = $ID" ;
$sql = "DELETE FROM Tasks WHERE task_id = $ID;";
echo $row['task_id'];
// $delete_query = "DELETE FROM Tasks WHERE task_id = ['task_id'] ";
/* if(isset($GET['task_id'])){
$delete = $_GET['task_id'];
mysqli_query($connect, "DELETE FROM Tasks WHERE task_id = '$delete'");
} */
echo("Succesfully deleted");
mysqli_close($link);
The script runs and it says "successfully deleted" but the entry still shows. In the F12 Menu/Network tab I get this
error
And when I click "view source" it shows the ID of the row. I can't seem to figure out what is wrong.
I am try to delete data using php pdo. and data can deleted successfully so you can try this code.
I have created 2 file. first req.php and second delete.php.
Here req.php file can fetch data and delete.php file can delete this data from send req.php file id.
req.php
<?php
require "connection.php";
//This is a fetch data from database
$sql = "SELECT * FROM test";
$select = $conn->prepare($sql);
$select->execute();
?>
<html>
<head>
<title>Data</title>
</head>
<body>
<table>
<thead>
<tr>
<th>ID</th>
<th>NAME</th>
<th>EMAIL</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<?php
while($data = $select->fetch())
{
?>
<tr>
<td><?php echo $data['id']; ?></td>
<td><?php echo $data['student_name']; ?></td>
<td><?php echo $data['email_address']; ?></td>
<td><button onclick="return conformation();">Delete</button></td> <!-- This is a delete data button --->
</tr>
<?php
}
?>
</tbody>
</table>
</body>
</html>
<script>
//This is a conformation function if it will return true then data can delete otherwise data cannot deleted.
function conformation() {
let conform = confirm("Can you delete this data ?");
if (conform == true) {
return true;
} else {
return false;
}
}
</script>
delete.php
<?php
require "connection.php";
if(isset($_GET['id']))
{
$sql = "DELETE FROM test WHERE id = ?";
$deleteData = $conn->prepare($sql);
if ($deleteData->execute([$_GET['id']]))
{
header('location: http://local.test/req.php');
}
}
?>
The first issue is trying to get task_id from REQUEST params while you sending "Delete" key.
The second is you passed the task_id to db as a string, while I think it's an Integer type in the database.
So you have to do that:
echo "<td><a href='delete.php?task_id=" . $row['task_id']."'>Delete"."</a>"."</td></tr>" . "$record->ID";
$task_id = mysqli_real_escape_string($connect, $_GET['task_id']);
if (!empty($task_id)) {
$delete_query = mysqli_query($connect, 'DELETE FROM Tasks WHERE task_id = '.$task_id);
if ($delete_query) {
echo 'deleted successfully';
} else {
echo("Error: " . mysqli_error($connect));
}
} else {
echo 'task_id is empty !';
}
You can solve this or debug it by doing the following.
parse the right URL parameter
echo "<td><a href='delete.php?task_id=" . $row['task_id']."'>Delete"."</a>"."</td></tr>" . "$record->ID";
this will send a task_id value to the delete page.
checking and logging the response of my SQL in delete.php
if(isset($_REQUEST['task_id'])){
//escape to avoid SQL injection
$delete = mysqli_real_escape_string($connect, $_REQUEST['task_id']);
$process = mysqli_query($connect, "DELETE FROM Tasks WHERE task_id = '".$delete."'");
if($process){
echo("Succesfully deleted");
}else{
echo("Error description: " . mysqli_error($connect));
}
}else{
echo("no id supplied");
}
in your question, you also had this: $GET['task_id'], which I believe was null.
I have a Delete.php page that deletes records based on their ID.
When there is an ID, i.e., Delete.php?id=3610, all is well, and it functions as expected.
If I just go to "Delete.php" and that's it - no ID, it generates:
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1"
From the little I understand, it is doing this because I am trying to pass a nonexistent variable into my query.
I have been trying to put if (empty($_POST['id'])) { } in different places, which removes the error, but breaks something else.
Here is my code:
<?php
require_once 'functions.php';
$conn = mysqli_connect("localhost", "user", "pass",'db');
writeHead("Delete Track");
if (isset($_POST['delete'])) {
$trkid = $_POST['trkid'];
$query = "DELETE FROM track WHERE TrackID=$trkid";
mysqli_query($conn, $query) or die(mysqli_error($conn));
if (mysqli_affected_rows($conn)>0) {
header("Location: Display.php?action=deleted&id=$trkid&status=deleted");
exit();
}
echo "<p class='error'>Unable to update record</p>";
} else {
if (!isset($_GET['id'])) {
echo "<p class='error'>No Track ID provided.<br><a href='Display.php'>Return to display page.</a><p>";
}
$trkid=$_GET['id'];
$query = "SELECT * FROM track WHERE TrackID=$trkid";
$result = mysqli_query($conn,$query);
if (!$result) {
die(mysqli_error($conn));
}
if (mysqli_num_rows($result)> 0) {
$row = mysqli_fetch_assoc($result);
$Name=$row['Name'];
$Album=$row['AlbumId'];
$Composer=$row['Composer'];
$Milli=$row['Milliseconds'];
$Bytes=$row['Bytes'];
$UnitPrice=$row['UnitPrice'];
} else {
echo "<p class='error'>Unable to retrieve Track $trkid.<br><a href='Display.php'>Return to display page.</a>";
}
}
?>
<p>Track Information:</p>
<p><?php echo "<b>ID: $trkid <br>Title: $Name</b>"; ?></p>
<form method="post" action="Comp3Delete.php">
<p>
<input type="hidden" name="trkid" value="<?php echo $trkid; ?>">
<input type="submit" name="delete" class="btn" value="Confirm Delete">
</p>
</form>
<p>Return to Track Table Display</p>
<?php writeFoot(); ?>
Your post code is fine. it's the GET code that's wrong:
if (!isset($_GET['id'])) {
^^^^^^^^--check if the parameter exists
}
$trkid=$_GET['id'];
^---try to use the parameter ANYWAYS, even if it doesn't exist.
$trkid=$_GET['id']; has no condition so it runs even when no id is passed which generates the error. Your code should go like this:
if(isset($_GET['id'])){
$trkid=$_GET['id'];
$query = "SELECT * FROM track WHERE TrackID=$trkid";
$result = mysqli_query($conn,$query);
if (!$result) {
die(mysqli_error($conn));
}
if (mysqli_num_rows($result)> 0) {
$row = mysqli_fetch_assoc($result);
$Name=$row['Name'];
$Album=$row['AlbumId'];
$Composer=$row['Composer'];
$Milli=$row['Milliseconds'];
$Bytes=$row['Bytes'];
$UnitPrice=$row['UnitPrice'];
} else {
echo "<p class='error'>Unable to retrieve Track $trkid.<br><a href='Display.php'>Return to display page.</a>";
}
}
I was trying to delete a record on my Database. So basically I created a table that contains all of my records. Now what I need to do is when I click on the "DELETE" link it would delete the record selected row.
Here's what it looks like:
So basically I have 3 pages here.
1. page.php
2. add.php
3. delete.php
Here's my page.php file:
<table border="1">
<thead>
<th>email</th>
<th>date</th>
<th>delete</th>
</thead>
<tbody>
<tr>
<?php
foreach($emails as $mail){ ?>
<td><?php echo $mail['email']; ?></td>
<td><?php echo $mail['date']; ?></td>
<td><?php echo "<a href='delete.php?id=". $mail['id']. "'>DELETE</a>"; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
Here's my add.php file:
<?php
require("new-connection.php");
session_start();
$email = $_POST['email'];
if(empty($_POST['email']) AND (filter_var($email, FILTER_VALIDATE_EMAIL) === false))
{
$_SESSION['message'] = "email cannot be blank";
}else{
$query = "INSERT INTO email_tbl (email, date)
VALUES('$email', NOW())";
$insertEmail = run_mysql_query($query);
if(run_mysql_query($query))
{
$_SESSION['message'] .= "New RECORD has been added correctly!";
}
else
{
$_SESSION['message'] .= "Failed to add new Interest";
}
}
header('Location: email.php');
?>
Here's my delete.php file so far:
<?php
require("new-connection.php");
session_start();
$query = "DELETE FROM email_tbl
WHERE id={id} LIMIT 1";
$deleteEmail = run_mysql_query($query);
if(run_mysql_query($query))
{
$_SESSION['message'] .= "RECORD has been DELETED correctly!";
}
else
{
$_SESSION['message'] .= "Failed to DELETE RECORD";
}
header('Location: email.php');
?>
So now when I click the delete link it must delete the button real time. Any idea?
Modify your delete.php to retrieve the url parameter:
<?php
require("new-connection.php");
session_start();
$id = $_GET['id'];
$query = "DELETE FROM email_tbl
WHERE id='$id' LIMIT 1";
$deleteEmail = run_mysql_query($query);
if($deleteEmail)
{
$_SESSION['message'] .= "RECORD has been DELETED correctly!";
}
else
{
$_SESSION['message'] .= "Failed to DELETE RECORD";
}
header('Location: email.php');
?>
As for your add.php, you are using this:
$insertEmail = run_mysql_query($query);
if(run_mysql_query($query))
You should change it to this:
$insertEmail = run_mysql_query($query);
if($insertEmail)
What you are doing right now is you are executing the query twice by calling run_mysql_query twice. This should fix it
Sense when what run_mysql_query a function in php?
http://php.net/manual-lookup.php?pattern=run_mysql_query&scope=quickref
Update the delete.php file:
$id = $_GET['id'];
$query = "DELETE FROM email_tbl WHERE id='$id' LIMIT 1";
and also check the section below:
You are running the query twice. so it is obvious it will add the same record twice.
$insertEmail = run_mysql_query($query);
if(run_mysql_query($query))
{
$_SESSION['message'] .= "New RECORD has been added correctly!";
}
Modify you code to use the run_mysql_query once only.
$query = "DELETE FROM email_tbl WHERE id=".$_GET['id']." LIMIT 1";
I am trying to add in a new row to a MySQL table. It is reading me the error Could not enter data: Column count doesn't match value count at row 1 . So far, I am using the code
if(! get_magic_quotes_gpc() )
{
$job_pos = addslashes ($_POST['job_pos']);
}
else
{
$job_pos = $_POST['job_pos'];
}
$job_pos_sort = "SELECT LAST(job_pos_sort) FROM careers;" + 1;
$sql = "INSERT INTO careers ".
"(job_pos, job_pos_sort) ".
"VALUES('$job_pos', '$job_pos_sort', NOW())";
to insert a new row into the table.
Here is my entire code for the page, my page can be seen at http://thetotempole.ca/phptester/upanddowntest.php :
<?php
// connect to db
$conn = mysql_connect("xxxx","x","x","x") or die(mysql_error());
$db = mysql_select_db('x',$conn) or die(mysql_error());
// if an arrow link was clicked...
if ($_GET['dir'] && $_GET['id']) {
// make GET vars easier to handle
$dir = $_GET['dir'];
// cast as int and couple with switch for sql injection prevention for $id
$id = (int) $_GET['id'];
// decide what row we're swapping based on $dir
switch ($dir) {
// if we're going up, swap is 1 less than id
case 'up':
// make sure that there's a row above to swap
$swap = ($id > 1)? $id-- : 1;
break;
// if we're going down, swap is 1 more than id
case 'down':
// find out what the highest row is
$sql = "SELECT count(*) FROM careers";
$result = mysql_query($sql, $conn) or die(mysql_error());
$r = mysql_fetch_row($result);
$max = $r[0];
// make sure that there's a row below to swap with
$swap = ($id < $max)? $id++ : $max;
break;
// default value (sql injection prevention for $dir)
default:
$swap = $id;
} // end switch $dir
// swap the rows. Basic idea is to make $id=$swap and $swap=$id
$sql = "UPDATE careers SET job_pos_sort = CASE job_pos_sort WHEN $id THEN $swap WHEN $swap THEN $id END WHERE job_pos_sort IN ($id, $swap)";
$result = mysql_query($sql, $conn) or die(mysql_error());
} // end if GET
// set a result order with a default (sql infection prevention for $sortby)
$sortby = ($_GET['sortby'] == 'job_pos')? $_GET['sortby'] : 'job_pos_sort';
// pull the info from the table
$sql = "SELECT job_pos_sort, job_pos FROM careers ORDER BY $sortby";
$result = mysql_query($sql, $conn) or die(mysql_error());
// display table
echo "<table border = '1'>";
echo "<tr>";
// make column names links, passing sortby
echo "<td><a href='{$_SERVER['PHP_SELF']}?sortby=job_pos_sort'>job_pos_sort</a></td>";
echo "<td><a href='{$_SERVER['PHP_SELF']}?sortby=job_pos'>job_pos</a></td>";
echo "</tr>";
// display data 1 row at a time
while ($r = mysql_fetch_assoc($result)) {
echo "<tr>";
// make the links to change custom order, passing direction and the custom sort id
echo "<td align = 'center'><a href='{$_SERVER['PHP_SELF']}?dir=up&id={$r['job_pos_sort']}'>/\</a> ";
echo "<a href='{$_SERVER['PHP_SELF']}?dir=down&id={$r['job_pos_sort']}'>\/</a></td>";
echo "<td>{$r['job_pos']}</td>";
echo "</tr>";
} // end while $r
echo "</table>";
// end display table
?>
<html>
<head>
<title>Manage Careers</title>
</head>
<body>
<?php
if(isset($_POST['add']))
{
$dbhost = 'x';
$dbuser = 'xx';
$dbpass = 'xx';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
if(! get_magic_quotes_gpc() )
{
$job_pos = addslashes ($_POST['job_pos']);
}
else
{
$job_pos = $_POST['job_pos'];
}
$job_pos_sort = "SELECT LAST(job_pos_sort) FROM careers;" + 1;
$sql = "INSERT INTO careers ".
"(job_pos, job_pos_sort) ".
"VALUES('$job_pos', '$job_pos_sort', NOW())";
mysql_select_db('x');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered 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">Job Position</td>
<td><input name="job_pos" type="text" id="job_pos"></td>
</tr>
<tr>
<td width="100"> </td>
<td> </td>
</tr>
<tr>
<td width="100"> </td>
<td>
<input name="add" type="submit" id="add" value="Add Job Position">
</td>
</tr>
</table>
</form>
<?php
}
?>
</body>
</html>
Any help is appreciated.
Regards,
Kelsey
I don't know what you are expecting to happen when specifying 2 columns, and trying to add 3
"INSERT INTO careers ".
"(job_pos, job_pos_sort) ".
"VALUES('$job_pos', '$job_pos_sort', NOW())
Googling the error would help you. It exactly tells what you are getting wrong.
columns job_pos, job_pos_sort, but values - job_pos, job_post_sort and NOW(). You might have to specify the last column, which seems to be a datetime one
I hope you also are aware the $job_pos_sort is just a string, and want evaluate to anything, especially with adding 1 to the string (it may rise an error too)
And, you'd better switch to one of the modern DB API's regarding mysql - mysqli or PDO.
http://www.php.net/manual/en/mysqlinfo.api.choosing.php
you should run this :
SHOW COLUMNS FROM careers;
then maybe we know the name of the field missing here xxxxxx
it must be a sort of date.
$sql = "INSERT INTO careers ".
"(job_pos, job_pos_sort, xxxxxx) ".
"VALUES('$job_pos', '$job_pos_sort', NOW())";
or simply try this:
$sql = "INSERT INTO careers ".
"(job_pos, job_pos_sort) ".
"VALUES('$job_pos', '$job_pos_sort')";
this should work
I'm creating an edit user profile for my project. I came across this error "
Notice: Undefined index: userid in C:\xampp\htdocs\HelloWorld\EditProfile.php on line 18
". I've spent an hour trying to find the cause of the error but I can't seem to find it. I followed this guide here php -'Edit' function for forum posts and such Here's my code:
EditProfile.php
<?php
// connect to SQL
$dbcnx = mysql_connect("localhost", "root", "2345fypj");
if (!$dbcnx)
{
echo( "<P>Unable to connect to the database server at this time.</P>" );
exit();
}
// connect to database
$dbcon = mysql_select_db("my_db", $dbcnx);
if (!$dbcon) {
echo( "<P>Unable to locate DB table at this time.</P>" );
exit();
}
//data preparation for the query
$id = intval($_GET['userid']);
// selects title and description fields from database
$sql = "SELECT * FROM user_profile WHERE userid=$id";
$result = mysql_query($sql) or die(mysql_error());
# retrieved by using $row['col_name']
$row = mysql_fetch_array($result);
?>
<h3>Edit</h3>
<form action="save_edit.php" enctype="multipart/form-data" method="post" name="myForm" />
<table>
<tr>
<td><b>Name</b></td>
<td><input type="text" size="70" maxlength="100" name="title" value="<?php echo $row['name'] ?>"></td>
</tr>
<tr>
<td><b>Age</b></td>
<td><input type="text" size="70" maxlength="100" name="title" value="<?php echo $row['age'] ?>"></td>
</tr>
</table>
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<input name="enter" type="submit" value="Edit">
</form>
<?php
mysql_close($dbcnx);
?>
save_edit.php
<?php
// connect to SQL
$con = mysql_connect("localhost", "root", "2345fypj");
if (!$con) {
echo( "<P>Unable to connect to the database server at this time.</P>" );
exit();
}
// connect to database
$dbcon = #mysql_select_db("user_profile", $con);
if (!$dbcon) {
echo( "<P>Unable to locate DB table at this time.</P>" );
exit();
}
#data preparation for the query
$id = intval($_POST["userid"]);
foreach ($_POST as $key => $value) $_POST[$key] = mysql_real_escape_string($value);
$sql = "UPDATE user_profile SET
name='$_POST[name]',
age='$_POST[age]',
WHERE userid=$id";
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
mysql_close($con);
header ("location: http://www.domain.com/url_to_go_to_after_update");
?>
Thanks in advance.
$id = intval($_GET['userid']);
It means set the $id variable to the "userid" variable in your URL. For example, if your URL is mySite.com?userid=12, $id will be set to "12". if your URL doesn't have "username=aValue" at the end section of it, you'll get the error you're seeing. :)
You could change it to this to set a default value:
$id = (isset($_GET['userid']) ? intval($_GET['userid']) : -1);
The problem is you're trying to use variable $_GET['userid'] while it's undefined. This variable refers to GET parameter in URL (e.g. EditProfile.php?userid=42). If this parameter isn't passed in URL, you will get this warning. You should check existence of variable:
if (!isset($_GET['userid'])) {
die("Parameter is missing!");
}
$id = intval($_GET['userid']);
You should probably be sure that the value is correctly set before trying to access it. Try using the isset function beforehand.
http://php.net/manual/en/function.isset.php
The problem with your code is apart from using a variable before its used, your continuing todo the query when setting to a default value with intval (will always return atleast 0), which if a non numeric character is passed your always going to update the row 0 user in the table, what you should be doing is not updating anything and returning the user with an error. You also have a rouge , after you age column in the query.
<?php
if(isset($_POST["userid"]) && is_numeric($_POST["userid"])){
$_POST = array_walk($_POST,'mysql_real_escape_string');
$sql = "UPDATE `user_profile` SET `name`='{$_POST['name']}', `age`='{$_POST['age']}'
WHERE `userid` = {$_POST['userid']}";
mysql_query($sql);
}else{
header('Location: ./failed');
}
?>