I'm trying to make a simple product page (no login or anything like that) in php and mysql.
So far, everything shows up on my products page fine, I can delete/add just fine from my admin page. From there I'm trying to figure out how to create an edit function.
So I made a form that populates from the mysql table based on the productid for convenience (edit2.php?id=X) which then posts to edit.php and hopefully updates the database.
So far, reusing the old code isn't working, somehow I was hoping it would be that simple.
This is my add product (which works) :
<?php
session_start();
if(isset($_POST) && isset($_POST['hp']) && empty($_POST['hp'])) {
if(
isset($_SESSION['token']) &&
$_SESSION['token'] == $_POST['token']
) {
mysql_connect('localhost', 'test_admin', 'test');
mysql_select_db('test_product');
$data = array_map('mysql_real_escape_string', $_POST);
$query = "
INSERT INTO products (
product_name, price, description, image
) VALUES (
'{$data['product_name']}',
'{$data['price']}',
'{$data['description']}',
'{$data['image']}'
)
";
if(mysql_query($query)) {
echo '<p>Your information was successfully saved.</p>';
unset($_SESSION['token']);
} else {
echo '<p>There was an error storing your data, please try again later.</p>';
}
} else {
echo '<p>Your data has already been saved.</p>';
}
} else {
echo '<p>Error.<br />Please try again later.</p>';
}
?>
This is my update (which just throws out a syntax error or 'error storing your data' :
<?php
mysql_connect('localhost', 'test_admin', 'test');
mysql_select_db('lbriedis_product');
$data = array_map('mysql_real_escape_string', $_POST);
$query = "UPDATE products WHERE id = ".$pageid." (
product_name, price, description, image
) VALUES (
'{$data['product_name']}',
'{$data['price']}',
'{$data['description']}',
'{$data['image']}'
)
";
if(mysql_query($query)) {
echo '<p>Your information was successfully saved.</p>';
unset($_SESSION['token']);
} else {
echo '<p>There was an error storing your data, please try again later.</p>';
echo mysql_error(); //Used for development and testing only
}
?>
I get session errors when I attempt to use session validation probably because I start a session on my admin page (add product form is on admin.php, edit and delete are links) ?
Nevertheless, I removed the session checks for the moment as I'm struggling more so with the update part.
Also I'm not sure of the best way to pass $pageid to the update query for 'update where id = $pageid. I have a hidden field with the value (see edit form), how do I reference this correctly?
Edit form (values display correctly so where id = $pageid is working here:
<?php
$dol = "$";
$pageid = (int)$_GET['id'];
mysql_connect('localhost', 'lbriedis_admin', 'xxxxxx123');
mysql_select_db('lbriedis_product');
$result = mysql_query("SELECT * FROM products WHERE id = ".$pageid."");
if($result){
$data = mysql_fetch_assoc($result);
}
?>
<form id="inputForm" method="post" action="edit.php">
<fieldset>
<label>Pool name:</label>
<?php
echo '<input type="text" name="product_name" value="'.$data['pool_name'].'" />';
?>
<label>Price:</label> <br>
<?php
echo '$ <input type="text" name="price" value="'.$data['price'].'" />';
?> <br />
<label>Description:</label>
<?php
echo '<textarea name="description">'.$data['description'].'</textarea>';
?>
<label>Image:</label></label>
<?php
echo '<input type="text" name="image" value="'.$data['image'].'" />';
?>
<input type="hidden" name="token" value="<?php echo $_SESSION['token']; ?>" />
<input type="text" id="hp" name="hp" />
<?php
echo '$ <input type="hidden" name="$pageid" value="'.$pageid.'" />';
?>
<br>
<input type="submit" name="submit" value="Update" />
</fieldset>
</form>
your update query have incorrect sintax
$query = "UPDATE products WHERE id = ".$pageid." (
product_name, price, description, image
) VALUES (
'{$data['product_name']}',
'{$data['price']}',
'{$data['description']}',
'{$data['image']}'
)
correct sintax should be
$query="UPDATE products SET
product_name = '".$data['product_name']."',
price ='".$data['price']."',
description = '".$data['description']."',
image = '".$data['image']."'
WHERE id = '".$pageid."'
change this
name="$pageid"
to
name="pageid"
and access it like this
$data = array_map('mysql_real_escape_string', $_POST);
$query = "UPDATE products WHERE id = {$data['pageid']} (
the problem was $pageid was not accessible in edit.php. And you have assigned $pageid to name attribute , which will be different fot each product.
Change the query to this
$query="UPDATE products SET
product_name = '{$data['product_name']}',
price ='{$data['price']}',
description = '{$data['description']}',
image = '{$data['image']}'
WHERE id = '{$data['pageid']}'
replace your update query with the below:-
$query = "UPDATE products
set product_name=$data['product_name'],
price = $data['price'],
description = $data['description'] ,
image = $data['image']
where id =". $pageid ;
Related
I would like to delete a row from an MySQL database. The row that I'd like to delete is displayed in a box, with each being obtained via a loop and SELECT statement.
I've already got the rows in the database being displayed accordingly; however, I'd like a button that once pressed, would delete the selected option from the database.
Here is my current code:
<form action="" method="post">
<label>Patient Name:</label>
<br><br>
<select name="patient" id="patient">
<?php
$conn = new mysqli("localhost", "root", "", "as2");
$result = $conn->query("SELECT patientID, patientName, address FROM patient ORDER BY patientName ASC");
while ($row = $result->fetch_assoc()){
$patientName = $row['patientName'];
$address = $row['address'];
echo "<option value=\"patient\">" .$patientName. ", ".$address."</option>";
}
?>
</select>
<input type="submit" name="delete" value="Delete Record">
</form>
How would I go about making the "Delete Record" button delete the selected option from the database?
first record (patientID) in a string
$patientID = $row['patientID'];
then Add $patientIDto (option value) so it become :
echo "<option value=".$patientID.">" .$patientName. ", ".$address."</option>";
then add this code After everything (ofc outside the "while" loop) :
<?php
$selected_patient = $_POST['patient'];
if( $_SERVER['REQUEST_METHOD'] === 'POST'
&& isset($_POST['delete']) && isset($_POST['patient']) ) {
if( !empty($_POST['patient']) ){
$patient_ID = mysql_real_escape_string($selected_patient);
if ( $conn->query("DELETE FROM patient WHERE patientID={$patient_ID}") )
echo "user has been deleted successfully";
else
echo "Error deleting";
}
}
?>
now you'r good to go , after click delete button refresh your page and Boom! , the user will Disappears
and if you want a real time Action u can use (Ajax)
Try this
while ($row = $result->fetch_assoc()){
$patientName = $row['patientName'];
$address = $row['address'];
$patientID = $row['patientID']; //get patient id
echo "<option value=\"$patientID\">" .$patientName. ", ".$address."</option>"; // change in option value
}
Now on form submit, you will get patient id in $_POST['patient'] , can write your delete query.
Hope this will hope.
I am having a problem.
I am creating a script that allows a person to select a record by it's primary ID and then delete the row by clicking a confirmation button.
This is the code with the form:
"confirmdelete.php"
<?php
include("dbinfo.php");
$sel_record = $_POST[sel_record];
//SQL statement to select info where the ID is the same as what was just passed in
$sql = "SELECT * FROM contacts WHERE id = '$sel_record'";
//execute SELECT statement to get the result
$result = mysql_query($sql, $db) or die (mysql_error());//search dat db
if (!$result){// if a problem
echo 'something has gone wrong!';
}
else{
//loop through and get dem records
while($record = mysql_fetch_array($result)){
//assign values of fields to var names
$id = $record['ID'];
$email = $record['email'];
$first = $record['first'];
$last = $record['last'];
$status = $record['status'];
$image = $record['image'];
$filename = "images/$image";
}
$pageTitle = "Delete a Monkey";
include('header.php');
echo <<<HERE
Are you sure you want to delete this record?<br/>
It will be permanently removed:</br>
<img src="$filename" />
<ul>
<li>ID: $id</li>
<li>Name: $first $last</li>
<li>E-mail: $email</li>
<li>Status: $status</li>
</ul>
<p><br/>
<form method="post" action="reallydelete.php">
<input type="hidden" name="id" value="$id">
<input type="submit" name="reallydelete" value="really truly delete"/>
<input type="button" name="cancel" value="cancel" onClick="location.href='index.php'" /></a>
</p></form>
HERE;
}//close else
//when button is clicked takes user back to index
?>
and here is the reallydelete.php code it calls upon
<?php
include ("dbinfo.php");
$id = $_POST[id];//get value from confirmdelete.php and assign to ID
$sql = "SELECT * FROM contacts WHERE id = '$id'";//where primary key is equal to $id (or what was passed in)
$result=mysql_query($sql) or die (mysql_error());
//get values from DB and display from db before deleting it
while ($row=mysql_fetch_array($result)){
$id = $row["id"];
$email = $row["email"];
$first= $row["first"];
$last = $row["last"];
$status = $row["status"];
include ("header.php");
//displays here
echo "<p>$id, $first, $last, $email, $status has been deleted permanently</p>";
}
$sql="DELETE FROM contacts WHERE id = '$id'";
//actually deletes
$result = mysql_query($sql) or die (mysql_error());
?>
The problem is that it never actually ends up going into the "while" loop
The connection is absolutely fine.
Any help would be much appreciated.
1: It should not be $_POST[id]; it should be $_POST['id'];
Try after changing this.
if it does not still work try a var_dump() to your results to see if it is returning any rows.
if it is empty or no rows than it is absolutely normal that it is not working.
and make sure id is reaching to your php page properly.
Ok as you are just starting, take care of these syntax, and later try switching to PDO or mysqli_* instead of mysql..
Two major syntax error in your code:
Parameters must be written in ''
E.g:
$_POST['id'] and not $_POST[id]
Secondly you must use the connecting dots for echoing variables:
E.g:
echo "Nane:".$nane; or echo $name; but not echo "Name: $name";
Similarly in mysql_query
E.g:
$sql = "SELECT * FROM table_name WHERE id="'.$id.'";
I hope you get it..take care of these stuff..
i have a site where you can send greeting messages via php to a mysql server, and an admin login page. In the admin login page, it shows all of the messages with a status either pending, rejected or accepted with the buttons reject and accept next to each message.
Currently, whenever I hit "accept" or "reject" ALL of the messages become rejected or accepted in the database. I'd like to have the buttons call the script with a parameter which is the id of the message they're accepting/rejecting but I honestly don't know the proper syntax. Any help would be greatly appreciated.
$query = "SELECT name, location, message, status FROM messages ORDER by status ";
if ($query_run = mysql_query($query))
{
while ($query_row = mysql_fetch_assoc($query_run))
{
$name = $query_row['name'];
$location = $query_row['location'];
$message = $query_row['message'];
$status = $query_row['status'];
echo '<form method="POST" action="login.php">';
echo 'From: '.$name.'<br>Location: '.$location.'<br>Status: '.$status.'<br>Message: '.$message.'<br><br>';
?>
<input type="submit" value="Approve" name="accept">
<input type="submit" value="Reject" name="reject"></form>
<?php
if (isset($_POST['accept']))
{
echo 'Accepted!';
$updateAccept = "UPDATE messages SET status = 'a'";
mysql_query($updateAccept);
};
if (isset($_POST['reject']))
{
echo 'Rejected!';
$updateAccept = "UPDATE messages SET status = 'r'";
mysql_query($updateAccept);
}
Bind a hidden field with each submit button like this
<form method="POST">
<input type="submit" value="Whatever" name="trigger_update" />
<input type="hidden" name="id_to_be_updated" value="<?php echo 'pass your id here'; ?>" />
</form>
<?php
if(isset($_POST['trigger_update'])) {
//Do sanitization according to your needs
mysqli_query($connection, "UPDATE tbl_name SET column_name = 'whatever' WHERE id = {$_POST['id_to_be_updated']}");
}
?>
You just need to add a WHERE clause in your UPDATE statement:
$updateAccept = "UPDATE messages SET status = 'a' WHERE id = '$id'";
This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
PHP UPDATE prepared statement
(3 answers)
Closed 11 months ago.
Can anybody help me understand why this update query isn't updating the fields in my database? I have this in my php page to retrieve the current values from the database:
<?php
$query = mysql_query ("SELECT * FROM blogEntry WHERE username = 'bobjones' ORDER BY id DESC");
while ($row = mysql_fetch_array ($query))
{
$id = $row['id'];
$username = $row['username'];
$title = $row['title'];
$date = $row['date'];
$category = $row['category'];
$content = $row['content'];
?>
Here i my HTML Form:
<form method="post" action="editblogscript.php">
ID: <input type="text" name="id" value="<?php echo $id; ?>" /><br />
Username: <input type="text" name="username" value="<?php echo $_SESSION['username']; ?>" /><br />
Title: <input type="text" name="udtitle" value="<?php echo $title; ?>"/><br />
Date: <input type="text" name="date" value="<?php echo $date; ?>"/><br />
Message: <textarea name = "udcontent" cols="45" rows="5"><?php echo $content; ?></textarea><br />
<input type= "submit" name = "edit" value="Edit!">
</form>
and here is my 'editblogscript':
<?php
mysql_connect ("localhost", "root", "");
mysql_select_db("blogass");
if (isset($_POST['edit'])) {
$id = $_POST['id'];
$udtitle = $_POST['udtitle'];
$udcontent = $_POST['udcontent'];
mysql_query("UPDATE blogEntry SET content = $udcontent, title = $udtitle WHERE id = $id");
}
header( 'Location: index.php' ) ;
?>
I don't understand why it doesn't work.
You have to have single quotes around any VARCHAR content in your queries. So your update query should be:
mysql_query("UPDATE blogEntry SET content = '$udcontent', title = '$udtitle' WHERE id = $id");
Also, it is bad form to update your database directly with the content from a POST. You should sanitize your incoming data with the mysql_real_escape_string function.
Need to add quote for that need to use dot operator:
mysql_query("UPDATE blogEntry SET content = '".$udcontent."', title = '".$udtitle."' WHERE id = '".$id."'");
Without knowing what the actual error you are getting is I would guess it is missing quotes. try the following:
mysql_query("UPDATE blogEntry SET content = '$udcontent', title = '$udtitle' WHERE id = '$id'")
Here i updated two variables and present date and time
$id = "1";
$title = "phpmyadmin";
$sql= mysql_query("UPDATE table_name SET id ='".$id."', title = '".$title."',now() WHERE id = '".$id."' ");
now() function update current date and time.
note: For update query we have define the particular id otherwise it update whole table defaulty
First, you should define "doesn't work".
Second, I assume that your table field 'content' is varchar/text, so you need to enclose it in quotes. content = '{$content}'
And last but not least: use echo mysql_error() directly after a query to debug.
Try like this in sql query, It will work fine.
$sql="UPDATE create_test set url= '$_POST[url]' WHERE test_name='$test_name';";
If you have to update multiple columns,
Use like this,
$sql="UPDATE create_test set `url`= '$_POST[url]',`platform`='$_POST[platform]' WHERE test_name='$test_name';";
you must write single quotes then double quotes then dot before name of field and after like that
mysql_query("UPDATE blogEntry SET content ='".$udcontent."', title = '".$udtitle."' WHERE id = '".$id."' ");
using a drop-down list that's populated from database fields, i need to select an option and then delete that from the database. i'm trying to do this by sending the form to a process php page where i pull in the select option from the post array and then delete it from the database and return to the index page.
having issues with getting the array variable from the post array. can anyone help with some code on how to get the variable and then delete the mysql title
<form method="post" action="deleteReview_process.php">
<select name="title">
<?php
while($row = mysql_fetch_array($sql_result)) {
$movieTitle = $row['title'];
?>
<option><?php echo $movieTitle; ?></option>
<?php } ?>
</select>
<input type="submit" name="delete" id="delete" value="delete" />
---- and the process page ---
include 'inc/db.inc.php';
if($_POST['delete']) {
$title = $_POST['title'][$movieTitle]; <------ NOT WORKING
$sql = "DELETE" . $title . "FROM pageTitle";
mysql_query($sql, $conn)
or die("couldn't execute query");
header("Location: http://localhost/cms/index.php");
}
else
{
header("Location: http://localhost/cms/deleteReview.php");
}
Because your SELECT element is named "title," it will be represented as $_POST["title"] when it arrives to the backend script:
$title = $_POST['title'];
Also, your query needs to be corrected:
$sql = "DELETE" . $title . "FROM pageTitle";
Should be:
$sql = "DELETE FROM tableName WHERE title = '{$title}'";
$title is going to be in $_POST['title'] ie. $title = $_POST['title']