I have 2 tables: product (id, name, quantity, c_id) and product_category (cat_id, cat_name).
I have the option to update the existing products. When I change the name and the quantity it works just fine, but when I try to change the product category the c_id doesn't change to the new one.
The code from the update page (update.php):
<?php
include 'database.php';
$id = $_POST['productId'];
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM product where id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($id));
$data = $q->fetch(PDO::FETCH_ASSOC);
$name = $data['name'];
$quantity = $data['quantity'];
Database::disconnect();
?>
<form id="updateFrom" action="update2.php" method="POST">
<table border="1" cellpadding="10">
<tr align='center'>
<td>Name</th>
<td><input name="name" type="text" value="<?php echo $name;?>"/></td>
</tr>
<tr align='center'>
<td>Quantity</th>
<td><input name="quantity" type="text" value="<?php echo $quantity;?>"/></td>
</tr>
<tr align='center'>
<?php $cat = $pdo->query("SELECT c_name, CATEGORY_ID FROM product_category");
?>
//Here the user selects the new category from the dropdown list
<td>Category</th>
<td>
<select name="c_id">
<?php
while ($rows = $cat->fetch(PDO::FETCH_ASSOC))
{
$cat_name = $rows['c_name'];
$cat_id = $rows['CATEGORY_ID'];
echo"<option value='$cat_id'>$cat_name</option>";
}
?>
</select>
</td>
</tr>
</table>
<input type="hidden" id="productId" name="productId" value="<?php echo $id;?>"/>
<button type="submit">update</button>
</form>
</body>
The code which makes the update (update2.php):
<?php
require 'database.php';
$id = null;
if ( !empty($_POST)) {
$id = $_POST['productId'];
$name = $_POST['name'];
$quantity = $_POST['quantity'];
// update data
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE product set name = ?, quantity = ? WHERE id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($name,$quantity,$id));
Database::disconnect();
header("Location: index.php");
}
?>
You need to set the c_id column from $_POST['c_id'].
if ( !empty($_POST)) {
$id = $_POST['productId'];
$name = $_POST['name'];
$quantity = $_POST['quantity'];
$category = $_POST['c_id'];
// update data
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE product set name = ?, quantity = ?, c_id = ? WHERE id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($name,$quantity,$category,$id));
Database::disconnect();
header("Location: index.php");
}
I also suggest that you have the existing category selected by default in the dropdown.
while ($rows = $cat->fetch(PDO::FETCH_ASSOC))
{
$cat_name = $rows['c_name'];
$cat_id = $rows['CATEGORY_ID'];
$selected = $cat_id == $data['c_id'] ? "selected" : "";
echo "<option value='$cat_id' $selected>$cat_name</option>";
}
I'm working on a CRUD system and currently, I am in the Update section. I have old values from users that need to be updated to new ones through an HTML form.
Right now I am trying to retrieve the POST values from the HTML form set to the post method. After that, I update the user info with the new values gained from the POST request.
<?php
$oldId = $_GET['id'];
$conn = mysqli_connect('localhost', 'root', '')
or die('Verbinding met database server is mislukt.');
mysqli_select_db($conn, 'crudopdracht')
or die('De database is niet beschikbaar');
$query = "SELECT * FROM gebruikers WHERE id = $oldId";
$result = mysqli_query($conn, $query)
or die (mysqli_error($conn));
while ($row = mysqli_fetch_assoc($result)){
$naam = $row['naam'];
$leeftijd = $row['leeftijd'];
$gender = $row['gender'];
$locatie = $row['locatie'];
};
?>
<form action="" method="post">
<label for="id">ID:</label><br>
<input type="text" id="id" name="id" <?php echo 'placeholder="' . $oldId . '"><br>';?>
<label for="naam">Naam:</label><br>
<input type="text" id="naam" name="naam" <?php echo 'placeholder="' . $naam . '"><br>';?>
<label for="leeftijd">Leeftijd:</label><br>
<input type="text" id="leeftijd" name = "leeftijd" <?php echo 'placeholder="' . $leeftijd . '"><br>';?>
<label for="gender">Geslacht:</label><br>
<input type="text" id="gender" name="gender" <?php echo '[placeholder="' . $gender . '"><br>';?>
<label for="locatie">Locatie:</label><br>
<input type="text" id="locatie" name = "locatie" <?php echo 'placeholder="' . $locatie . '"><br><br>';?>
<input type="submit" value="Verstuur" id="submit" name="submit">
</form>
</div>
<?php
if(isset($_POST["submit"])){
echo 'hello';
$id = $_POST["id"];
$naam = $_POST["naam"];
$leeftijd = $_POST["leeftijd"];
$gender = $_POST["gender"];
$locatie = $_POST["locatie"];
$query2 = "UPDATE gebruikers SET id = $id, naam = $naam, leeftijd = $leeftijd, gender = $gender, locatie = $locatie WHERE id = $oldId";
mysqli_query($conn,$query2);
}
?>
In my opinion, I expect the values to change to the new ones set in the HTML form, but they always return the old values.
SQL injection issues aside (as you've stated it isn't in scope of the particular issue), you need to correctly format your SQL query for any non-integer values, so that they are encapsulated with quotes ('[value]').
Your query would current run as:
UPDATE gebruikers ( id = somevalue, naam = somevalue, leeftijd = somevalue, gender = somevalue, locatie = somevalue WHERE id = 12345`
In this query, SQL would attempt to interpret your values as entities (columns, tables), which is obviously not what you want.
So, although you should never inject user input values into a query, the following should fix your issue:
Change
$query2 = "UPDATE gebruikers SET id = $id, naam = $naam, leeftijd = $leeftijd, gender = $gender, locatie = $locatie WHERE id = $oldId";
to
$query2 = "UPDATE gebruikers SET id = $id, naam = '$naam', leeftijd = '$leeftijd', gender = '$gender', locatie = '$locatie' WHERE id = $oldId";`
Assuming id is an INT field, and the others are strings.
I am trying to do a simple edit/update of my data in the database. But somehow it will not work.
So I am able to read out the saved data into the form. I also don't have any errors
I have stared at my code and googled for hours but I don't see where I might have made a mistake with my code.
The printed echo gives the following output which seems to be right:
HTML code:
<form id="formAddCategory" class="FrmCat" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<div class="form-group">
<!-- hidden id from tbl -->
<input type="hidden" name="hiddenId" value="<?php echo $hiddenID ?>" />
<label for="recipient-name" class="control-label">Category Name:</label>
<input type="text" class="form-control" id="recipient-name1" name="category" required="" value="<?php echo $category ?>" />
</div>
<button type="submit" id="btnEditCat" class="btn btn-danger" name="editCategory">Save Category</button>
</form>
Part of my php code to edit/update:
<?php
//edit/update data to db
if(isset($_POST['editCategory'])){
$categoryUpdate = mysqli_real_escape_string($con, $_POST['category']);
$categoryID = mysqli_real_escape_string($con, $_POST['hiddenId']);
$qry = "UPDATE tbl_Category SET category = $categoryUpdate WHERE category_id = $categoryID";
$result = mysqli_query($con, $qry);
echo $qry;
if($result){
header("Location: category.php");
}
}
?>
You need single quote ' to wrap your parameter:
$qry = "UPDATE tbl_Category SET category = '$categoryUpdate' WHERE category_id = '$categoryID'";
You should use single quotes (') for values
$qry = "UPDATE tbl_Category SET category = '$categoryUpdate' WHERE category_id = '$categoryID'";
Also you can use like this to avoid SQL injection (See here)
$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// do something with $row
}
Once again I am at the mercy of your knowledge and hope you can help.
Actual question is the bold italics, however you won't be able to help without reading the information that I've given.
Background to Question - I'm creating a photography website (for my mum) using HTML, CSS, MySQL and PHP. I'm in the process of working on the database, specifically on allowing my mum to insert images into the database using this form (http://i.imgur.com/h4nXFFA.png). She has no idea how to code, therefore I need to make it easy for her.
Database Background (what you need to know) - I've got an image_tbl and album_tbl. The album_tbl is shown here - http://i.imgur.com/4GXh9MP.png - with each album having an ID and Name (forget the 'hidden'). The image_tbl is shown here - http://i.imgur.com/RgC35Nd.png - with the important part (for this question) being the albumName.
Aim - I've managed to populate the 'Insert a New Image' form with the albums from album_tbl (picture shows 'Exploration'). I want her to be able to click the AlbumName (so she knows what album to add to), yet I want the image she inserts to receive the albumID in the database. Here's a Pastebin of my code thus far.
http://pastebin.com/6v8kvbGH = The HTML Form, for helping me be aware of the 1st Form in the code...
http://pastebin.com/4X6abTey = PHP/MySQL Code. Here we have me calling the inputs in the form and using them in 2 SQL Queries. The first Query is aiming to get the albumID of the albumName that was entered, and this is where it goes wrong. The commented out statements (using //) are me error-checking, and albumName is passed on from the form. However, the number of rows returned from the 1st SQL Statement is 0, when it should be 1. This is where I need help as clearly something's wrong with my assoc array ...
2nd Aim - Once the 1st SQL Query is working, the 2nd SQL Query is hopefully going to input the required variables into image_tbl including the albumID I hopefully just got from the 1st SQL Query.
I hope this is all that's required, as far as I'm aware the people who understand this should be able to help with what I've given. Thanks very much in advance!
Jake
Someone asked me to paste the code - HTML Form:
<h2>Insert a new image</h2><br>
<form action="imagesInsert.php" method="POST" enctype="multipart/form-data">
Name of Image: <input type="text" name="name" /><br>
Date: <input type="text" name="dateTime" /><br>
Caption: <input type="text" name="caption" /><br>
Comment: <textarea type="text" name="comment" cols="40" rows="4"></textarea><br>
Slideshow: <input type="text" name="slideshow" /><br>
Choose an Album to place it in:
<?php
mysql_connect('localhost', 'root', '');
mysql_select_db('admin_db');
$sql = "SELECT albumName FROM album_tbl WHERE hidden = false";
$result = mysql_query($sql); ?>
<select name='albumName'>; <?php
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['albumName'] . "'->" . $row['albumName'] . "</option>";
}
?> </select>
<input type="submit" name="submit"/><br>
</form>
<h2>Hide the Image</h2><br>
<form action="imagesHidden.php" method="POST" enctype="multipart/form-data">
Title:
<?php
mysql_connect('localhost', 'root', '');
mysql_select_db('admin_db');
$sql = "SELECT name FROM image_tbl WHERE hidden = false";
$result = mysql_query($sql);
echo "<select name='name'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['name'] . "'>" . $row['name'] . "</option>";
}
echo "</select>";
?>
<input type="submit" value="Hide" name="submit">
</form>
<h2> Renew from Hidden Items </h2><br>
<form action="imagesRestore.php" method="POST" enctype="multipart/form-data">
Title:
<?php
mysql_connect('localhost', 'root', '');
mysql_select_db('admin_db');
$sql = "SELECT name FROM image_tbl WHERE hidden = true";
$result = mysql_query($sql);
echo "<select name='name'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['name'] . "'>" . $row['name'] . "</option>";
}
echo "</select>";
?>
<input type="submit" value="Renew / Un-Hide" name="submit">
</form>
</body>
Inserting the image using PHP/MySQL:
<?php
$username="root";
$password="";
$database="admin_db";
$servername="localhost";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully <br><hr>";
$name = $_POST['name'];
$dateTime = $_POST['dateTime'];
$caption = $_POST['caption'];
$comment = $_POST['comment'];
$slideshow = $_POST['slideshow'];
$hidden = false;
$albumName = $_POST['albumName'];
// echo "album name is" . $albumName;
$sql = "SELECT albumID FROM album_tbl WHERE albumName = $albumName";
$albumID = $conn->query($sql);
// echo "Number of rows is " . $albumID->num_rows;
if ($albumID->num_rows > 0) {
// output data of each row
while($row = $albumID->fetch_assoc()) {
echo "Album ID: " . $row["albumID"]. "<br>";
}
} else {
echo "0 results";
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$new_comment = str_replace("'", "''", $comment);
$sql = "INSERT INTO `image_tbl`(`name`, `dateTime`, `caption`, `comment`, `slideshow`, `hidden`, `albumID`) VALUES ('$name', '$dateTime', '$caption', '$new_comment', '$slideshow', '$hidden', '$albumID')";
$result = $conn->query($sql);
if ($result)
{
echo "Data has been inserted";
}
else
{
echo "Failed to insert";
}
$conn->close();
?>
This line:
$sql = "SELECT albumID FROM album_tbl WHERE albumName = $albumName";
should be:
$sql = "SELECT albumID FROM album_tbl WHERE albumName = '$albumName'";
since the album name is a string.
You should check for errors when you perform a query:
$albumID = $conn->query($sql) or die($conn->error);
You can't use $albumID in the INSERT query. Despite the name of the variable, it doesn't contain an album ID, it contains a mysqli_result object that represents the entire resultset of the query -- you can only use it with methods like num_rows and fetch_assoc() to extract information from the resultset.
What you can do is use a SELECT statement as the source of data in an UPDATE:
$stmt = $conn->prepare("INSERT INTO `image_tbl`(`name`, `dateTime`, `caption`, `comment`, `slideshow`, `hidden`, `albumID`)
SELECT ?, ?, ?, ?, ?, ?, albumID
FROM album_tbl
WHERE albumName = ?";
$stmt->bind_param("sssssss", $name, $dateTime, $caption, $comment, $slideshow, $hidden, $albumName);
$stmt->execute();
Note that when you use a prepared query, you don't need to fix the quotes in $comment (which you should have done using $conn->real_escape_string($comment), not str_replace()).
Just to help you understand, this can also be done without a prepared query.
$sql = "INSERT INTO `image_tbl`(`name`, `dateTime`, `caption`, `comment`, `slideshow`, `hidden`, `albumID`)
SELECT '$name', '$dateTime', '$caption', '$new_comment', '$slideshow', '$hidden', albumID
FROM album_tbl
WHERE albumName = '$albumName'";
First of all create a single database connection let say
db_connection.php
<?php
$username="root";
$password="1k9i2n8gjd";
$database="admin_db";
$servername="localhost";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully <br><hr>";
Then in your form or any php file that needs database connection you can just include the db_connection.php so that you have one database connection.
Note: I have change the value of option to albumId so that you dont need to query or select based on albumName because you already have the albumID passed in imagesInsert.php via $_POST
<?php
require_once('db_connection.php');
//include_once('db_connection.php');
?>
<html>
<head>
<title>Admin Page | Alison Ryde's Photography</title>
<link rel="stylesheet" type="text/css" href="../../css/style.css">
</head>
<body>
<h2>Insert a new image</h2><br>
<form action="imagesInsert.php" method="POST" enctype="multipart/form-data">
Name of Image: <input type="text" name="name" /><br>
Date: <input type="text" name="dateTime" /><br>
Caption: <input type="text" name="caption" /><br>
Comment: <textarea type="text" name="comment" cols="40" rows="4"></textarea><br>
Slideshow: <input type="text" name="slideshow" /><br>
Choose an Album to place it in:
<?php
$sql = "SELECT albumName FROM album_tbl WHERE hidden = false";
$result = $conn->query($sql);// mysql_query($sql); ?>
<select name='albumName'>; <?php
while ($row = $result->fetch_array()) {
echo "<option value='" . $row['albumID'] . "'->" . $row['albumName'] . "</option>";
}
?> </select>
<input type="submit" name="submit"/><br>
</form>
<h2>Hide the Image</h2><br>
<form action="imagesHidden.php" method="POST" enctype="multipart/form-data">
Title:
<?php
$sql = "SELECT name FROM image_tbl WHERE hidden = false";
$result = $conn->query($sql);//mysql_query($sql);
echo "<select name='name'>";
while ($row = $result->fetch_array()) {
echo "<option value='" . $row['name'] . "'>" . $row['name'] . "</option>";
}
echo "</select>";
?>
<input type="submit" value="Hide" name="submit">
</form>
<h2> Renew from Hidden Items </h2><br>
<form action="imagesRestore.php" method="POST" enctype="multipart/form-data">
Title:
<?php
$sql = "SELECT name FROM image_tbl WHERE hidden = true";
$result = $conn->query($sql);//mysql_query($sql);
echo "<select name='name'>";
while ($row = $result->fetch_array()) {
echo "<option value='" . $row['name'] . "'>" . $row['name'] . "</option>";
}
echo "</select>";
?>
<input type="submit" value="Renew / Un-Hide" name="submit">
</form>
</body>
</html>
Then in your php code that inserts the data should be like this.
imagesInsert.php
<?php
require_once('db_connection.php');
//include_once('db_connection.php');
$name = $_POST['name'];
$dateTime = $_POST['dateTime'];
$caption = $_POST['caption'];
$comment = $_POST['comment'];
$slideshow = $_POST['slideshow'];
$hidden = false;
$albumID = $_POST['albumName'];
$new_comment = str_replace("'", "''", $comment);
$sql = "INSERT INTO `image_tbl`(`name`, `dateTime`, `caption`, `comment`, `slideshow`, `hidden`, `albumID`) VALUES ('$name', '$dateTime', '$caption', '$new_comment', '$slideshow', '$hidden', '$albumID')";
$result = $conn->query($sql);
if ($result)
{
echo "Data has been inserted";
}
else
{
echo "Failed to insert";
}
$conn->close();
?>
Another piece of advice is to use prepared statementif your query is build by users input to avoid sql injection
<?php
require_once('db_connection.php');
//include_once('db_connection.php');
$name = $_POST['name'];
$dateTime = $_POST['dateTime'];
$caption = $_POST['caption'];
$comment = $_POST['comment'];
$slideshow = $_POST['slideshow'];
$hidden = false;
$albumID = $_POST['albumName'];
$new_comment = str_replace("'", "''", $comment);
$sql = "INSERT INTO `image_tbl`(`name`, `dateTime`, `caption`, `comment`, `slideshow`, `hidden`, `albumID`) VALUES (?, ?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sssssss", $name, $dateTime, $caption,$new_comment,$slideshow,$hidden,$albumID);
$stmt->execute();
hope that helps :) good luck
The below code will only work with one checkbox and ignores the rest. Is there any way that I can have it to delete selected checkboxes? I have tried using implode but it gives me
Warning: implode(): Invalid arguments passed
<form action="" method="post">
<input type="checkbox" name="id" class="check" value = "<?php echo $row['id']; ?>">
<?php echo $row['to_user'];?>
<input type="submit" name="delete">
</form>
<?php
if (isset($_POST['delete'])) {
$id = $_POST['id'];
$ids = implode( ',', $id );
$mydb = new mysqli('localhost', 'root', '', 'database');
$stmt = $mydb->prepare("update messages set deleted = 'yes' where from_user = ? and id = ? ");
$stmt->bind_param('ss', $user, $ids);
$stmt->execute();
echo "Message succesfully deleted";
exit();}
?>
Give the checkbox an array-style name:
<input type="checkbox" name="id[]" class="check" value = "<?php echo $row['id']; ?>">
This will cause $_POST['id'] to be an array of all the checked values. Then delete them in a loop:
$mydb = new mysqli('localhost', 'root', '', 'database');
$stmt = $mydb->prepare("update messages set deleted = 'yes' where from_user = ? and id = ?");
$stmt->bind_param('ss', $user, $id);
foreach ($_POST['id'] as $id) {
$stmt->execute();
}
You can't use a comma-separated list of IDs with =. You can use it with id in (...), but you can't do parameter substitution with this because the number of elements isn't known. So the loop is th best way to do it.