Update SQL database with preparedStatement in Java
The code is now working. Thanks for Prashant for his answer. Once slightly adapted it worked well
String query = ("UPDATE TB01 SET BLADETYPE=?,STARTT1=?,AIRT1=?,FOAMT1=?,SCT1=?,FINISHT1=? WHERE SERIAL=?");
try (PreparedStatement pstmt = conn.prepareStatement(query)) {
pstmt.setString(7, bladeSerial);
pstmt.setString(1, itemText);
pstmt.setString(2, String.valueOf(startTime1));
pstmt.setString(3, String.valueOf(airTime1));
pstmt.setString(4, String.valueOf(foamTime1));
pstmt.setString(5, String.valueOf(scTime1));
pstmt.setString(6, String.valueOf(finishTime1));
pstmt.executeUpdate();
}
catch (SQLException ex) {
// Exception handling
Logger.getLogger(FormTwo1.class.getName()).log(Level.SEVERE, null, ex);
}
Note as SERIAL had moved to the end of the string, the order also needed changing on the setString commands.
php update query using prepared statement not working
Add $stmt->close();
before your next mysqli
interaction.
if(sendMail($email,$verify_key)) { // send mail first then update DB
$stmt->close();
$query = " UPDATE `signup` SET `name`=?,`password`=?,`verify_key`=? WHERE `email`=? ";
or you might just always want to execute the close
after you're finished with your previous mysql
interaction.
e.g.:
$query = " SELECT active FROM signup WHERE email=?";
$stmt = $conn->prepare($query);
$stmt->bind_param("s",$email);
$stmt->execute();
$stmt->bind_result($dbactive);
$stmt->close();
and remove the $stmt->close();
from the if
. I've never seen official documentation on this but I've seen other threads were this was an underlying issue. The manual page itself actual almost states the opposite:
So, while explicitly closing open connections and freeing result sets is optional, doing so is recommended.
that is optional
is false (... in my experience, I also primarily use PDO).
How to prepare statement for update query?
An UPDATE
works the same as an insert or select. Just replace all the variables with ?
.
$sql = "UPDATE Applicant SET phone_number=?, street_name=?, city=?, county=?, zip_code=?, day_date=?, month_date=?, year_date=? WHERE account_id=?";
$stmt = $db_usag->prepare($sql);
// This assumes the date and account_id parameters are integers `d` and the rest are strings `s`
// So that's 5 consecutive string params and then 4 integer params
$stmt->bind_param('sssssdddd', $phone_number, $street_name, $city, $county, $zip_code, $day_date, $month_date, $year_date, $account_id);
$stmt->execute();
if ($stmt->error) {
echo "FAILURE!!! " . $stmt->error;
}
else echo "Updated {$stmt->affected_rows} rows";
$stmt->close();
PHP UPDATE prepared statement
$stmt = $this->mysqli->prepare("UPDATE datadump SET content=? WHERE id=?");
/* BK: always check whether the prepare() succeeded */
if ($stmt === false) {
trigger_error($this->mysqli->error, E_USER_ERROR);
return;
}
$id = 1;
/* Bind our params */
/* BK: variables must be bound in the same order as the params in your SQL.
* Some people prefer PDO because it supports named parameter. */
$stmt->bind_param('si', $content, $id);
/* Set our params */
/* BK: No need to use escaping when using parameters, in fact, you must not,
* because you'll get literal '\' characters in your content. */
$content = $_POST['content'] ?: '';
/* Execute the prepared Statement */
$status = $stmt->execute();
/* BK: always check whether the execute() succeeded */
if ($status === false) {
trigger_error($stmt->error, E_USER_ERROR);
}
printf("%d Row inserted.\n", $stmt->affected_rows);
Re your questions:
I get a message from my script saying 0 Rows Inserted
This is because you reversed the order of parameters when you bound them. So you're searching the id column for the numeric value of your $content, which is probably interpreted as 0. So the UPDATE's WHERE clause matches zero rows.
do I need to declare all the fields or is it ok to just update one field??
It's okay to set just one column in an UPDATE statement. Other columns will not be changed.
Multiple update query in single prepare execute statement mysql
Try this. you have to pass comma separated list of the ids you have to update as the first argument of your procedure. Hope this helps.
DELIMITER $$
CREATE PROCEDURE proc_name(IN strIDs VARCHAR(255))
BEGIN
DECLARE strLen INT DEFAULT 0;
DECLARE SubStrLen INT DEFAULT 0;
IF strIDs IS NULL THEN
SET strIDs = '';
END IF;
do_this:
LOOP
SET strLen = LENGTH(strIDs);
update tableName
set column2 = 'a', column3 = 'b'
where column1 = SUBSTRING_INDEX(strIDs, ',', 1);
SET SubStrLen = LENGTH(SUBSTRING_INDEX(strIDs, ',', 1));
SET strIDs = MID(strIDs, SubStrLen, strLen);
IF strIDs = NULL THEN
LEAVE do_this;
END IF;
END LOOP do_this;
END
$$
DELIMITER ;
UPDATE query using prepared statement with multiple WHERE conditions
In MySql you can do tuples comparasion.
So you can do something like this
UPDATE bla
SET x=123
WHERE (x,y) in ((12,13),(13,13),(25,23),(37,33),(39,13),(44,23),(54,33),(84,23),(94,23),(99,33))
How to UPDATE in database using mysqli prepared statement?
For procedural way
$query = "UPDATE `crew_info` SET `updated_photo` = ? WHERE `id` = ?";
$stmt = mysqli_prepare($conn, $query);
// you should use i instead of s for id
mysqli_stmt_bind_param($stmt, 'si', $imageData, $_GET['id']);
mysqli_stmt_execute($stmt);
Try this out in object-oriented style
$query = "UPDATE `crew_info` SET `updated_photo` = ? WHERE `id` = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param("si", $imageData, $_GET['id']);
$stmt->execute();
Related Topics
Pass Extra Parameters to Usort Callback
How to Send a Status Code in PHP, Without Maintaining an Array of Status Names
Subquery in Doctrine2 Notin Function
Jquery Ajax Returns the Whole Page
Trim Unicode Whitespace in PHP 5.2
Ini_Set("Memory_Limit") in PHP 5.3.3 Is Not Working at All
Why Is Constructing Pdo Connection Slow
How to Prepare Statement for Update Query
Split String into Sentences Using Regex
Is This a How to Destroy All Session Data in PHP
Inserting into MySQL from PHP (Jquery/Ajax)
How to Show a Where Clause Just for One Field in MySQL
Best Methods to Clean Up a Hacked Site with No Clean Version Available