How do I update multiple tables using prepared statements with mySQLi? - php

I have a form with two fields with the name attribute of 'photo_title' and 'photographer_name', and a hidden field named 'photo_id'. When the user pushes the submit button, i want it to update two separate tables in the database. I can get it to update a single table, but as soon as I try to leftjoin the second table, it doesn't like it.
I think there may be something wrong with my query string or the binding. How can I update two separate values in two separate tables in my Mysql database while still using prepared statements?
Here's the PHP:
if (array_key_exists('update', $_POST)) {
$sql = 'UPDATE photos SET photos.photo_title = ?, photographers.photographer_name = ?
LEFT JOIN photographers ON photos.photographer_id = photographers.photographer_id
WHERE photo_id = ?';
$stmt = $conn->stmt_init();
if ($stmt->prepare($sql)) {
$stmt->bind_param('ssi', $_POST['photo_title'], $_POST['photographer_name'], $_POST['photo_id']);
$done = $stmt->execute();
}
}
Here's the form:
<form id="form1" name="form1" method="post" action="">
<input name="photo_title" type="text" value=""/>
<textarea name="photographer_name"></textarea>
<input type="submit" name="update" value="Update entry" />
<input name="photo_id" type="hidden" value="<?php echo $photo_id ?>"/>
</form>

Here's an answer so folks who read this question see it, instead of finding it in your comment above. I'll mark this CW so I don't get any points for it.
UPDATE photos LEFT JOIN photographers
ON photos.photographer_id = photographers.photographer_id
SET photos.photo_title = ?, photographers.photographer_name = ?
WHERE photos.photo_id = ?
FWIW, the documentation for MySQL's UPDATE syntax is illustrative.

I was working on something similar. Here is a few things that I did. Hope it helps
if (isset($_POST['update'])) {
$id=intval($_GET['photo_id']);
$photo_title=$_POST['photo_title'];
$photographer_name=$_POST['photographer_name'];
$sql = "update photos p, photographers pg set p.photo_title=:photo_title, pg.photographer_name=:photographer_name where p.photographer_id=$id and pg.photographer_id=$id";
$query = $dbh->prepare($sql);
$query->bindParam(':photo_title',$photo_title,PDO::PARAM_STR);
$query->bindParam(':photographer_name',$photographer_name,PDO::PARAM_STR);
$query->execute();
}
You can even add your photo_id to the form action in case you want to use the id on a different page.
<form id="form1" name="form1" method="post" action="index.php?id=<?php echo $photo_id;?>">
<input name="photo_title" type="text" value=""/>
<textarea name="photographer_name"></textarea>
<input type="submit" name="update" value="Update entry" />
</form>
I have a file I created that connects to the database that I named config that has the following codes. Include it with this code where your form is at the top so you don't get errors executing the code above.
<?php
// DB credentials.
define('DB_HOST','localhost');
define('DB_USER','root');
define('DB_PASS','');
define('DB_NAME','photographer');
// Establish database connection.
try{
$dbh = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME,DB_USER,
DB_PASS,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
}
catch (PDOException $e){
exit("Error: " . $e->getMessage());}
?>

Related

PHP update form that updates database information only if there is an input in that particular field using PDO

I am currently working on a form that uses PHP and SQL to update information in a database. It is functioning properly and updating the information but the issue is... is that it updates everything, including fields that I didn't even put any input in which means it will only update a particular row in the database and leave the others blanks... I need it to just change information from a field with an actual input and leave it if there is no input.
Here is the PHP and SQL code:
try {
$deleteRecId = $_GET['id'];
$update_event_name = $_POST['updateName'];
$update_event_location = $_POST['updateLocation'];
$update_event_date = $_POST['updateDate'];
include 'connect.php';
if(isset($_POST["submit"])) {
// new data
$sql = "UPDATE events SET event_name='$update_event_name',
event_location='$update_event_location', event_date='$update_event_date'
WHERE event_id=$deleteRecId";
// Prepare statement
$stmt = $conn->prepare($sql);
// execute the query
$stmt->execute();
// echo a message to say the UPDATE succeeded
echo $stmt->rowCount() . " records UPDATED successfully";
}
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
and here if the form:
<form class="update-form" action="<?php echo $_PHP_SELF ?>" method="post">
<p id="input-headers">Event Name</p>
<p id="update-input-field-wrapper">
<input type="text" name="updateName" value="">
</p>
<p id="input-headers">Event Location</p>
<p id="update-input-field-wrapper">
<input type="text" name="updateLocation" value="">
</p>
<p id="input-headers">Event Date</p>
<p id="update-input-field-wrapper">
<input type="text" name="updateDate" value="" placeholder="01/01/2000">
</p>
<input type="submit" name="submit" value="Submit" id="updateBtn">
</form>
So to sum up I need this application to only update information of a field with an actual input and if the form field has no input I need that database info to remain the same. I appreciate any help with this as I am pretty new to these concepts... thanks!
I found a really handy solution to this! Here is how I implemented it into my code.
$sql = "UPDATE events SET event_name=IF(LENGTH('$update_event_name')=0, event_name, '$update_event_name'), event_location=IF(LENGTH('$update_event_location')=0, event_location, '$update_event_location'), event_date=IF(LENGTH('$update_event_date')=0, event_date, '$update_event_date') WHERE event_id=$deleteRecId";
It basically just checks whether the string is empty or not. If it's empty it won't be updated. If it isn't empty it'll go through with the update! Very simple way to achieve this effect when creating an update form.
Using your current code structure, you can do this.
Use SQL to select * from event ID. Populate your update_event_xxx with the parameters.
If $_POST[xx] is blank, ignore. Else, update_event_xx = $_POST[xx]

PHP query for copying tables

This has to be somewhere online but I am having no luck after hours of trying to do this.
So I've HTML form on one page and a PHP page that creates a database fine..
<form action="createdb.php" method="post">
<label for="dbname"><b>Name of DB</b></label>
<input type="text" name="dbname" id="dbname"/>
<input type="submit" value="Create DB">
<?php
$conn = mysqli_connect("localhost", "root", "") or die(mysqli_error());
$dbname = $_POST['dbname'];
if (mysqli_query($conn,"CREATE DATABASE $dbname")) {
echo "Database created";
} else {
echo "Database was not created";
}
mysqli_close($conn);
?>
Then I have underneath the PHP code these forms.. The form for creating the tables work fine within the DB that has just been created.. But its the form for copying tables from a DB already created into the newly created DB.
<form action="createtable.php" method="post">
<label for="tablename"><b>Create Table within new DB</b></label>
<input type="text" name="tablename" id="tablename"/>
<input type="hidden" name="holdname" value="<?php echo $dbname ?>">
<input type="submit" value="Create Table">
</form>
<p>OR</p>
<form action="copytables.php" method="post">
<label for="tablename"><b>Copy RSS Tables</b></label>
<input type="text" name="tablename" id="tablename" readonly/>
<input type="hidden" name="holdname" value="<?php echo $dbname ?>">
<input type="submit" value="Copy Tables">
</form>
I wanted to copy the tables, structure and data called 'lookup_age' and 'score' into the new DB from a database called 'rss_db'. I've rewrote the PHP page needed in many different ways and ATM it has been left like this, as of something I seen on W3schools, which confused me even more. I know it can be easily done via PHPMYADMIN but need it through a query now and HTML form if possible. Heres what I have as followed but wondering what should the query line actually be if possible..
<?php
$conn = mysqli_connect("localhost", "root", "") or die(mysqli_error());
$dbname =$_POST['holdname'];
mysqli_select_db($conn,"$dbname");
mysqli_select_db($conn,"rss_db");
$sql = "
INSERT lookup_age
INTO $dbname
FROM rss_db";
mysqli_close($conn);
?>
I don't know if these will help but you could try:
create table `table2` like `table1`;
insert `table2` select * from `table`;
or, as a single line perhaps
create table `table2` as select * from `table1`;
try this query, to copy the tables:
$sql = " create table '$dbname' as select * FROM 'rss_db'";
FINALLY FOUND IT!! As simple as...
$query = "INSERT INTO $dbname.lookup_age
SELECT * FROM rss_db.lookup_age";

Form to delete data from MySQL database using PHP

So I'm creating a small program with 2 forms, one to add data to a database, and one to delete from it. I've managed to create the first input form, but I'm slightly confused as to how I would get the second form to work. In the database "tasks" I have a table called "ID" which has the columns "ID", "Name" and "Hours"
Here's what the two HTML forms look like
<h2>Add Tasks</h2>
<form action="test.php" method="get">
Name of Task: <input type="text" name="name"><br />
Hours: <input type="number" name="hours"><br />
<input type="submit" value="Add" name="submit">
</form>
<h2>Delete Tasks</h2>
<form action="delete.php" method="get">
ID: <input type="number" name="ID"><br />
<input type="submit" value="Delete">
</form>
And the PHP for the first form "Add tasks" which inserts data
$servername = "localhost";
$username = "root";
$password = "root";
$conn = new mysqli($servername, $username, $password, "Tasks");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
};
if (isset($_GET['submit'])) {
mysqli_select_db ($conn,"Tasks");
$name = $_GET['name'];
$hours = $_GET['hours'];
$sql = "INSERT INTO ID (Name, Hours) VALUES ('".$name."','". $hours."')";
$results = mysqli_query($conn,$sql);
$query = "SELECT `Name` FROM `ID`";
$result = mysqli_query($conn, $query);
$x=0;
And the PHP for the second form which deletes tasks. This is the part that is not working
if (isset($_GET['submit'])) {
mysqli_select_db ($conn, "Tasks");
$id = $_GET['id'];
$sql = "DELETE FROM ID (ID) VALUES ('".$id."')";
$query = "SELECT `Name` FROM `ID`";
$result = mysqli_query($conn, $query);
$x=0;
How should I format the PHP for the second button. I've basically reused the code for the first form. Do I need to differentiate it somehow from the first button? Currently the page is showing up completely blank. I'm a complete novice so any help would be appreciated.
Your SQL Statement
"DELETE FROM ID (ID) VALUES ('".$id."')"
is wrong.
It should be
DELETE FROM table_name
WHERE some_column=some_value;
. So, change your statement to
DELETE FROM ID WHERE ID='$id'
Suggestions
You should use POST method for action which will result in data edit.
You should check the input, make sure it did not contain SQL statement. A good way is to use $stuff = mysql_real_escape_string($_GET["stuff"]).
I see you have name 'ID' in the form but your are trying to get 'id'. That could be the problem
The sql statement for deletion should look something like the snippet below.
$sql = "DELETE FROM ID WHERE `id`=".$id.";";
$results = mysqli_query($conn,$sql);
In addition to above answers you should give different name to the both form input tags as
<h2>Add Tasks</h2>
<form action="test.php" method="get">
Name of Task: <input type="text" name="name"><br />
Hours: <input type="number" name="hours"><br />
<input type="submit" value="Add" name="submit">
</form>
<h2>Delete Tasks</h2>
<form action="delete.php" method="get">
ID: <input type="number" name="ID"><br />
<input type="submit" value="Delete" name="delete">
</form>
So for adding into database , you can use
if (isset($_GET['submit'])){
// your code here
}
And for deleting from database , you can use
if (isset($_GET['delete'])){
mysqli_select_db ($conn, "Tasks");
$id = $_GET['id'];
$sql = "DELETE FROM ID (ID) WHERE ID='".mysql_real_escape_string($id)."' ;
$query = "SELECT `Name` FROM `ID`";
$result = mysqli_query($conn, $query);
$x=0;
}
This will solve all the problems.
If you are using same name for the type="submit" in both forms than you can use POST method on one form and GET method on the other.
And yes mysql_real_escape_string is used to prevent SQL INJECTION.

Identifying specific row from SQL results

I have a list of 'orders' being pulled out, which consist of product name, description etc, one of the fields is quantity which is in an editable text box, next to that is an update button (which has an unique ID for that row pulled from the DB). Now when the update button is pressed, I want the quantity for that product to be updated. However i'm having problems getting the correct updated quantity to be matched with the ID of that row.
I can see that the problem is me setting the $quantity1 variable with just the last result pulled out inside the IF statement, but I can't think how to get it to relate the row i'm clicking on. Here is part of the code:
echo "<td>".$row['uName']."</td>";
echo "<td>".$row['prodID']."</td>";?>
<form method="post" action="reserved.php">
<td><input name="quantity1" type="text" id="quantity1" size="1" value='<?= $qty ?>' />
<td><input name="order2" id="order2" type="submit" class="button_add" value='<?= $row['ID']?>' /></td><?
echo "</tr>";
}
}elseif(!empty($studyDir) && $rowCount == 0){
?>
<?
}
}
if (isset($_POST['order2'])){
$order2 = $_POST['order2'];
$quantity1 = $_POST['quantity1'];
\\echo $quantity1;
$link3 = mysql_connect('localhost', '******', '******');
$SQL1 = "UPDATE ybsinter_stock.reservedStock SET qty = $quantity1 WHERE ID = '$order2'";
$result1 = mysql_query($SQL1);
mysql_close($link3);
unset($quantity1);
unset($order2);
header("Location:reserved.php");
}
?>
I can't see your form ending i.e. there is no <\form>.
Also note that declaring forms in tables (except entirely enclosed in a td) is bad HTML, run your code through the W3C validator.
Also try PHP heredocs for outputting blocks of HTML with embedded data....
echo <<<EOF
<tr>
<td>{$row['uName']}</td>
<td>{$row['prodID']}</td>
<td>
<form method="post" action="reserved.php">
<input name="quantity1" type="text" id="quantity1" size="1" value="{$qty}" />
// style this button right with CSS if you want ...
<input name="order2" id="order2" type="submit" class="button_add" value="{$row['ID']}" />
</form>
</td>
</tr>
EOF;
The above form will only submit data to your script with the id that you're interested in..
Your SQL query seems roughly correct, but beware of SQL injection - please bind your variables into your queries instead of inserting them. Use the mysqli or PDO libraries instead of the outdated basic mysql functions.
$mysqli = new mysqli( /* your connection params here */ );
$sql1 = 'UPDATE ybsinter_stock.reservedStock SET qty = ? WHERE ID = ?';
$stmt = $mysqli->query( $sql1);
$stmt->bind_param( 'sd', $quantity1, $order2);
$result = $stmt->execute();

Issue with inserting value into a database

what is the issue with this code , I'm using a form to insert some values into a database , i have a controller setup like that. when i submit the form , the value was not posted in the database, but if i remove all others fields and left only 2 fields in the form and post it ,it works so there's something that i miss,been trying to resolve for more than 6 hours .please some help :
//database insertion
if (isset($_POST['VideoTITLE']))
if (isset($_POST['ByArtist']))
if (isset($_POST['GroupName']))
if (isset($_POST['URL']))
if (isset($_POST['VideoDate']))
{
try
{
$sql = 'INSERT INTO videoclip SET
VideoTITLE = :VideoTITLE,
ByArtist = :ByArtist,
GroupName = :GroupName,
URL = :URL,
VideoDate = CURDATE()
';
$s = $pdo -> prepare($sql);
$s -> bindValue(':VideoTITLE',$_POST['VideoTITLE']);
$s -> bindValue(':ByArtist',$_POST['ByArtist']);
$s -> bindValue(':GroupName',$_POST['GroupName']);
$s -> bindValue(':URL',$_POST['URL']);
$s -> execute();
}
catch(PDOException $e)
{
$error = 'error adding submitted data' . $e-> getMessage();
include 'error.html.php';
exit();
}
header('Location:.');
exit();
}
here's my html form setup:
<form action="?" method="post" class="form-horizontal">
<legend>Song Info</legend>
<fieldset>
<label>Song Title </label>
<input type="text" id="VideoTITLE" name="VideoTITLE" placeholder="song name…">
<label>Artist </label>
<input type="text" id="ByArtist" name="ByArtist" placeholder="artist name…">
<label>Musical Group</label>
<input type="text" id="GroupName" name="GroupName" placeholder="Type something…">
<label>Poster link</label>
<input type="text" id="URL" name="URL" placeholder="Type something…">
</fieldset><br>
<input type="submit" class="btn btn-success" value="Post video">
</form>
Its a couple of problems, maybe more:
You have isset($_POST['VideoDate']) in your if condition which will always be false since VideoDate is not in your form. You should take this out since you seem to want to set it using CURDATE() in your insert script.
your insert statement is incorrect. mysql inserts typically look like INSERT INTO TABLE_NAME (COL1, COL2) values('VALUE1', 'VALUE2'); so you should change your insert code to look like
$sql = 'INSERT INTO videoclip (VideoTITLE, ByArtist, GroupName, URL, VideoDate) values (:VideoTITLE, :ByArtist, :GroupName, :URL, CURDATE())';
Your syntax is incorrect for INSERT. It should be something like:
$sql = 'INSERT INTO videoclip (VideoTITLE, ByArtist, GroupName, URL, VideoDate)
VALUES (:VideoTITLE, :ByArtist, :GroupName, :URL, CURDATE())';
In addition, $_POST['VideoDate'] is not valid as you do not have it in your form.
You're doing the if statements wrong.
if (isset($_POST['VideoTITLE']) && isset($_POST['ByArtist']) && isset($_POST['GroupName'])
&& isset($_POST['URL']) && isset($_POST['VideoDate'])) {
....
}
This is basic programming stuff, so you might want to get a good introductory book to programming or PHP.

Categories