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.
Related
I am trying to figure out mysqli (I am just a starting scripter). I created the following script to grab 3 different values from my database. And it prints it on the screen in different textareas and input fields.
What I want to be able to do is when I press the update button that it'll update the records in the database for the form where the button is attached to.
Can anyone give me some tips on how to achieve something like that?
<?php
$sqlserver = <SQLSERVER>;
$sqluser = <SQLUSER>;
$sqlpassword = <SQLPASSWORD>;
$sqldatabase = <SQLDATABASE>;
$mysqli = new mysqli($sqlserver, $sqluser, $sqlpassword, $sqldatabase);
$loggedinuserid= "5";
$standaardtekstlabel = $mysqli->query("SELECT standaardtekst_label FROM Standaardteksten WHERE standaardtekst_account_pID='".$loggedinuserid."'");
$standaardtekstnl = $mysqli->query("SELECT standaardtekst_tekst FROM Standaardteksten WHERE standaardtekst_account_pID='".$loggedinuserid."'");
$standaardteksten = $mysqli->query("SELECT standaardtekst_tekst_en FROM Standaardteksten WHERE standaardtekst_account_pID='".$loggedinuserid."'");
while ($NL_Tekst = mysqli_fetch_row($standaardtekstnl))
{
$label_Tekst = mysqli_fetch_row($standaardtekstlabel);
$EN_Tekst = mysqli_fetch_row($standaardteksten);
print '<form action="" method="POST">
<input type="text" name="standaardtekst_label" value=' . $label_Tekst[0] . '>
<textarea name="standaardtekst_tekst">' . $NL_Tekst[0] . '</textarea>
<textarea name="standaardtekst_tekst_en">' . $EN_Tekst[0] . '</textarea>
<input type="submit" value="update">
</form>';
}
?>
First of all, there is absolutely 0.0 reason why you're using 3 queries for the information you're trying to get. You can simply have: $standaardtekst = $mysqli->query("SELECT standaardtekst_label,standaardtekst_tekst,standaardtekst_en FROM Standaardteksten WHERE standaardtekst_account_pID='".$loggedinuserid."'");
Now regarding your question that is now probably obsolete:
Make the names of the input like this: standaardtekst_tekst[] saving it in an array.
You also need to have a unique(auto increment) key in your database like: id and put it in every form. You can even use the value of this field in the name like this: standaardtekst_tekst[$id].
You could edit your code a bit to look something like this:
<?php
$sqlserver = <SQLSERVER>;
$sqluser = <SQLUSER>;
$sqlpassword = <SQLPASSWORD>;
$sqldatabase = <SQLDATABASE>;
$mysqli = new mysqli($sqlserver, $sqluser, $sqlpassword, $sqldatabase);
$loggedinuserid= "5";
$q = $mysqli->query("SELECT standaardtekst_id, standaardtekst_label,
standaardtekst_tekst, standaard_tekst_tekst_en
FROM Standaardteksten
WHERE standaardtekst_account_pID='".$loggedinuserid."'");
while ($NL_Tekst = mysqli_fetch_row($standaardtekstnl))
{
$row = mysqli_fetch_row($q);
?>
<form action="" method="POST">
<input type="text" name="formData[<?= $row['id']; ?>][standaardtekst_label]" value="<?= $row['standaardtekst_label']; ?>">
<textarea name="formData[<?= $row['id']; ?>][standaardtekst_tekst]"><?= $row['standaardtekst_tekst']; ?></textarea>
<textarea name="formData[<?= $row['id']; ?>][standaardtekst_tekst_en]"><?= $row['standaardtekst_tekst_en']; ?></textarea>
<input type="submit" value="update">
</form>
<?php
}
?>
What I've done:
Made your 3 queries into a single query
Gave each form a unique id
Cleaned up the code a bit
This enables you to do the following:
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['formData'])) {
foreach ($_POST['formData'] as $id => $value) {
$stmt = $mysqli->query("UPDATE standaardtekst SET standaardtekst_label='".$value['standaadtekst_label']."', standaardtekst_tekst='".$value['standaardtekst_tekst']."', standaardtekst_tekst_en='".$value['standaardtekst_tekst_en']."' WHERE standaardtekst_id='".$id."'");
}
}
Thx for the help everyone. Everything is working right now.
This is the script i used to get it to work :-)
<?php
$sqlserver = <SQLSERVER>;
$sqluser = <SQLUSER>;
$sqlpassword = <SQLPASSWORD>;
$sqldatabase = <SQLDATABASE>;
$mysqli = new mysqli($sqlserver, $sqluser, $sqlpassword, $sqldatabase);
$loggedinuserid= "5";
$result = $mysqli->query("SELECT * FROM Standaardteksten WHERE standaardtekst_account_pID='".$loggedinuserid."'");
$row_s = $result->fetch_assoc();
do{
print '<form action="" method="POST">
<input type="text" name="standaardtekst_label" value=' . $row_s['standaardtekst_label'] . '>
<textarea name="standaardtekst_tekst">' . $row_s['standaardtekst_tekst'] . '</textarea>
<textarea name="standaardtekst_tekst_en">' . $row_s['standaardtekst_tekst_en'] . '</textarea>
<input type="text" name="standaardtekst_ID" value="'. $row_s['standaardtekst_ID'] .'"/>
<input type="submit" value="update">
</form>';
} while($row_s = $result->fetch_assoc());
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['standaardtekst_ID']))
{
$updatesql= sprintf("UPDATE Standaardteksten SET standaardtekst_label='%s', standaardtekst_tekst='%s', standaardtekst_tekst_en='%s' WHERE standaardtekst_ID='%s'",
$_POST[standaardtekst_label],
$_POST[standaardtekst_tekst],
$_POST[standaardtekst_tekst_en],
$_POST[standaardtekst_ID]
);
$mysqli->query($updatesql);
echo "Het volgende wordt aangepast: <br />", "Label:", $_POST[standaardtekst_label], "<br />" , "NL tekst:", $_POST[standaardtekst_tekst], "<br />" , "EN tekst:", $_POST[standaardtekst_tekst_en];
echo "<meta http-equiv='refresh' content='1;url=/form.php'>";
}
?>
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
Trying to update 1 row at a time using php.
I want to enable users to update products they have already added to a database, I have a simple form with the relevant fields:
<fieldset><legend><span> Update a product in the database! </span></legend>
<form id ="productsform" method="post" onsubmit="return false;" enctype="multipart/form-data">
<label> Product name: <input type="text" id="name" name="name"/> </label>
<label> Product quantity: <input type="number" id="quantity" name="quantity"/> </label>
<label> Product description: <input type="text" id="description" name="description"/> </label>
<label> Product price: <input type="text" id="price" name="price"/> </label>
</br>
<input id="submit" name="submit" type="button" class="reg" value="Update Product">
<div id="update"></div>
</form>
I am using ajax which is working correctly according the console, but im struggling with the php side of updating the rows:
<?php
include("dbase/config_database.php");
$id = $_POST["id"];
$name = $_POST['name'];
$quantity = $_POST['quantity'];
$description = $_POST['description'];
$price = $_POST['price'];
$query = "UPDATE products SET name = '{$name}', quantity = '{$quantity}', description = '{$description}', price = '{$price}'
WHERE id = {$id}";
mysqli_query($mysqli, $query);
?>
Here is the initial file I use to add the products to the database:
<?php
include("dbase/config_database.php");
//Stores all information passed through AJAX into the query
$name = $_POST['name'];
$quantity = $_POST['quantity'];
$description = $_POST['description'];
$price = $_POST['price'];
//Adds information to database
$query = "INSERT INTO products (name, quantity, description, price) VALUES ('$name','$quantity','$description','$price')";
//Runs the query
$result = $mysqli->query($query) OR die("Failed query $query");
echo $mysqli->error."<p>";
echo "Product Added";
$querynew = ("SELECT id as 'collectid' from products WHERE name = '$name'and quantity = '$quantity'and description ='$description'and price = '$price'");
$resultnew = $mysqli->query($querynew) OR die("Failed query $querynew");
while($info = mysqli_fetch_array( $resultnew)){
$productid = $info['collectid'];
}
$image = $_FILES['file1']['name'];
$type = $_FILES['file1']['type'];
$size = $_FILES['file1']['size'];
$tmp_name = $_FILES['file1']['tmp_name'];
$imgpath = "images/".$productid.".jpg";
// Run the move_uploaded_file() function here
$moveResult = move_uploaded_file($tmp_name, $imgpath);
// Evaluate the value returned from the function if needed
$querytwo = ("SELECT * FROM products WHERE name = '$name' and quantity = '$quantity' and description = '$description' and price = '$price'");
$resulttwo = $mysqli ->query($querytwo) OR die ("Failed query $querynew");
$info = array();
while($row = mysqli_fetch_assoc($resulttwo)){
$product = array("id" => $row ['id'],
"name" => $row ['name'],
"quantity" => $row ['quantity'],
"description" => $row ['description'],
"price" => $row ['price'],
);
array_push($info,$product);
}
$json_output = json_encode($info);
echo $json_output;
?>
Any help is much appreciated! I have messed around with the update php because im sure the problem is in there but cant find it.
You are not getting the $_POST["id"] from the form,because there is no input element with name id.
when you get all the data from the table then put the id in the form as a hidden field
like
<input type="hidden" name="id" value="<?=$row['id']?>">
then after submitting the form you'll get the id value in $_POST['id']
Always try to debug your code thoroughly try to print the query then you can easily know what is happening actually.All the best
My form is:
<form class="form-horizontal" action="update.php?id=<?php echo $id ?>" method="post">
$sql = 'SELECT * FROM prekes WHERE pirkejo_id=' . $pirkejas . '';
$q = $pdo->prepare($sql);
$prekes = array();
foreach ($pdo->query($sql) as $row) {
if ($row['prek_pav'] != '') {
array_push($prekes, $row);
}
}?>
<input name="prekes[1][pavadinimas]" type="text" value="<?php echo $prekes[0]['prek_pav']?>">
<input name="prekes[1][kaina]" type="text" value="<?php echo $prekes[0]['prek_kaina'] ?>">
<input name="prekes[2][pavadinimas]" type="text"value="<?php echo $prekes[1]['prek_pav']?>">
<input name="prekes[2][kaina]" type="text" value="<?php echo $prekes[1]['prek_kaina'] ?>">
I dont know how to optimize it. I want to update my records in database and have no idea how to pass prekes_id value to UPDATE sql.
I found that My update updates all records with the last value from my form. all recors are same as last entered.
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE customers set name = ?, pavarde = ?, ak = ?, numeris = ? WHERE id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($name, $pavarde, $ak, $numeris, $id));
foreach ($prekes as $preke) {
$sql = "UPDATE prekes SET prek_pav= ?,prek_kaina=? WHERE prekes_id=".$preke['prekes_id'];
$q = $pdo->prepare($sql);
$q->execute(array($preke['pavadinimas'], $preke['kaina']));
}
Database::disconnect();
header("Location: default.php");
I use this code to solve this. Are there any better working solution to this problem?
My table prekes (prekes_id, pirkejo_id, prek_pav, prek_kaina). I take pirkejo_id from $_POST['id'].
My question deals with my next/previous buttons. I can get my update/delete buttons to work, but I'm so ready to tear out my hair when dealing with the next/previous buttons. Any help would be spectacular! Here's my code. Also, I'm pretty new to PHP so if this is bad coding, please let me know and point me in the right direction so I can fix my mistakes. Thanks!!!
session_start();
include "connectionfile.php";
if (isset($_POST['fname']) &&
isset($_POST['lname']) &&
isset($_POST['email']) &&
isset($_POST['login']) &&
isset($_POST['password']) &&
isset($_POST['super']) &&
isset($_POST['foldername']))
{
$id = get_post('id');
$fname = get_post('fname');
$lname = get_post('lname');
$email = get_post('email');
$login = get_post('login');
$password = hash('sha256', get_post('password'));
$super = get_post('super');
$foldername = get_post('foldername');
if ($_POST['submit']==0){
$query = mysql_query("SELECT * FROM `Logins` WHERE ID < '".$id."' ORDER BY ID DESC LIMIT 1;");
while($row = mysql_fetch_array($query)){
$id = $row['ID'];
$fname = $row['fname'];
$lname = $row['lname'];
$email = $row['email'];
$login = $row['login'];
$password = $row['password'];
$super = $row['super'];
$foldername = $row['foldername'];
}
}else if ($_POST['submit']==1){
$query = "UPDATE Logins SET fname = '$fname', lname='$lname', email='$email".'#carouselclinical.com'."', login='$login', password='$password', super='$super', foldername='$foldername'";
$query .= "WHERE ID = '$id';";
if (!mysql_query($query, $connect))
echo "INSERT failed: $query<br />" .
mysql_error() . "<br /><br />";
}else if($_POST['submit']==2){
$delete_query = "DELETE FROM Logins WHERE ID = '".$id."';";
mysql_query($delete_query);
$rc = mysql_affected_rows();
echo "Rows Affected " . $rc;
}
if ($_POST['submit']==3){
$query = mysql_query("SELECT * FROM `Logins` WHERE ID= '". $id ."' ORDER BY ID ASC LIMIT 1;");
while($row = mysql_fetch_array($query)){
$id = $row['ID'];
$fname = $row['fname'];
$lname = $row['lname'];
$email = $row['email'];
$login = $row['login'];
$password = $row['password'];
$super = $row['super'];
$foldername = $row['foldername'];
}
}
}
mysql_close($connect);
function get_post($var)
{
return mysql_real_escape_string($_POST[$var]);
}
?>
<form action="" method="post"><pre>
id <input type="text" readonly="readonly" name="id" value="<?php echo "$id"; ?>" />
First Name <input type="text" name="fname" value="<?php echo "$fname"; ?>" />
Last Name <input type="text" name="lname" value="<?php echo "$lname"; ?>" />
Email <input type="text" name="email" value="<?php echo "$email"; ?>" /> There's no need to put #carouselclinical.com.
Login <input type="text" name="login" value="<?php echo "$login"; ?>"/>
Password <input type="text" name="password" value="<?php echo "$password"; ?>"/>
Super? <input type="text" name="super" value="<?php echo "$super"; ?>" />
foldername <input type="text" name="foldername" value="<?php echo "$foldername"; ?>" />
<button name="submit" value="0">Previous</button>
<button name="submit" value="1">UPDATE</button>
<button name="submit" value="2">Delete</button>
<button name="submit" value="3">Next</button>
</pre>
Home <br />
Log out
</form>
Try adding an else right above mysql_close($connect);. My guess is that on the initial page load you are not posting any values, so no action is taken. This will create a default ID if none is defined in your top if.
else{
$query = mysql_query("SELECT * FROM `Logins` ORDER BY ID ASC LIMIT 1;");
while($row = mysql_fetch_array($query)){
$id = $row['ID'];
$fname = $row['fname'];
$lname = $row['lname'];
$email = $row['email'];
$login = $row['login'];
$password = $row['password'];
$super = $row['super'];
$foldername = $row['foldername'];
}
Also, on your if ($_POST['submit']==3), you need to change the = to > in your $query so you can get the next record. Currently you would be selecting the same ID, not the next higher.
$query = mysql_query("SELECT * FROM `Logins` WHERE ID > '". $id ."' ORDER BY ID ASC LIMIT 1;");
Finally, when doing Previous/Next you also need to take into consideration how you will deal with Previous when you are on the first ID, and Next when you are on the last id, as you will return an empty result set from MySQL.