arbitrary value from checkbox causes hard time executing SQL statement on PDO - php

Sirs! I have a php script that handles multiple row update with PDO.
I want to add a checkbox that updates my database specific column by timestamp 30days from now if ticked.
The problem is ofc, when it is not ticked, there would be no value sent to its key, so I would end up with: It returns this error
Uncaught exception 'PDOException' with message SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use...
So I'm asking for help if there's turn around for this, here is my PHP code:
if (isset($_POST['submit'])) {
$stmt = $db->prepare("UPDATE `$tbl_name` SET `ssl`=:ssl, `exp`=:exp, `country`=:country, WHERE id=:id");
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->bindParam(':ssl', $ssl, PDO::PARAM_STR);
$stmt->bindParam(':exp', $exp, PDO::PARAM_STR);
$stmt->bindParam(':country', $country, PDO::PARAM_STR);
foreach ($_POST['ssl'] as $id => $ssl) {
if(isset($_POST['thirtydays'][$id])){
$exp = $_POST['thirtydays'][$id];
}
$country = $_POST['country'][$id];
$stmt->execute();
}
echo '<h1>Updated the records.</h1>';
}
exp is the timestamp column. Here is the checkbox as HTML:
<input type="checkbox" name="thirtydays[80]" value="2014-02-04 04:04:53">
<input type="text" name="country[80]" value="DE" />
<input type="text" name="ssl[80]" value="false"/>
Note the structure: thirtydays[$id], the timestamp in value is generated by date( "Y-m-d H:i:s",strtotime("+30 days"))
Hope somebody can help me. Thanks in advance and more power.

$exp=''; $country=''; $ssl='';
if (isset($_POST['submit'])) {
$stmt = $db->prepare("UPDATE `$tbl_name` SET `ssl`=:ssl, `exp`=:exp, `country`=:country WHERE id=:id");
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->bindParam(':ssl', $ssl, PDO::PARAM_STR);
$stmt->bindParam(':exp', $exp, PDO::PARAM_STR);
$stmt->bindParam(':country', $country, PDO::PARAM_STR);
foreach ($_POST['ssl'] as $id => $ssl) {
if(isset($_POST['thirtydays'][$id])){ $exp = $_POST['thirtydays'][$id]; }
$country = $_POST['country'][$id];
$stmt->execute();
}
echo '<h1>Updated the records.</h1>';

Query is executed only when checkbox is checked since if (isset($_POST['thirtydays'][$id]))
Also you set the $exp variable after you bind it to statement.
Same goes to $country variable
if (isset($_POST['submit'])) {
$stmt = $db->prepare("UPDATE `$tbl_name` SET `ssl`=:ssl, `exp`=:exp, `country`=:country WHERE id=:id");
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->bindParam(':ssl', $ssl, PDO::PARAM_STR);
foreach ($_POST['ssl'] as $id => $ssl) {
if(isset($_POST['thirtydays'][$id])){
$exp = $_POST['thirtydays'][$id];
} else {
$exp = '';
}
$country = $_POST['country'][$id];
$stmt->bindParam(':exp', $exp, PDO::PARAM_STR);
$stmt->bindParam(':country', $country, PDO::PARAM_STR);
$stmt->execute();
}
echo '<h1>Updated the records.</h1>'; }
You have comma just before WHERE in your statement. This may be the problem.

To all who wonders (probably) what's actually wrong with the OP's code: inside the UPDATE `$tbl_name` SET `ssl`=:ssl, `exp`=:exp, `country`=:country, WHERE id=:id, the comma before WHERE is a syntax error. That's all.

Related

errore SQLstate 23000 i can t save some values of JSON into my database

I need to save some values of a JSON into my database SQL.
Database - Table "confrontations"
This is my PHP code
require_once("database.php");
$apiURL = 'https://nico.planethoster.world/api-foot/confrontations/lire.php?annee=2020&semaine=29';
$response = file_get_contents($apiURL);
$jsonResponse = json_decode($response, true);
$items = $jsonResponse['match'];
foreach ($items as $item ) {
$query = "INSERT INTO `confrontations`(`id_match`, `id_equipe1`, `id_equipe2`, `cote1`, `coteN`, `cote2`, `date`, `heure`, `semaine`)
VALUES (:id_match, :id_equipe1, :id_equipe2, :cote1, :coteN, :cote2, :date, :heure, :semaine) ";
$check = $pdo->prepare($query);
$date = $item["date"];
$heure = $item["heure"];
$check->bindParam(':id_match', $item["id_match"], PDO::PARAM_INT);
$check->bindParam(':id_equipe1', $item["id_equipe1"], PDO::PARAM_INT);
$check->bindParam(':id_equipe2', $item["id_equipe2"], PDO::PARAM_INT);
$check->bindParam(':cote1', $item["cote1"], PDO::PARAM_STR);
$check->bindParam(':coteN', $item["coteN"], PDO::PARAM_STR);
$check->bindParam(':cote2', $item["cote2"], PDO::PARAM_STR);
$check->bindValue(':date', $date, PDO::PARAM_STR);
$check->bindValue(':heure', $heure, PDO::PARAM_STR);
$check->bindParam(':semaine', $item["semaine"], PDO::PARAM_INT);
$check->execute();
and that s my error
You are trying to save a row where the primary key (id_match) already exists. So multiple confrontations use the same id_match.
Maybe you already ran this code once. If you run it the second time you have to implement some update routine instead of an insert. E.g. UPDATE confrontations SET x = y WHERE id_match = z;

PDO: date not inserting, suggestions?

I'm trying to insert a date into the database using the following code, I get the following error: Error: SQLSTATE[22007]: Invalid datetime format: 7 ERROR: invalid input syntax for type date: ""
So the date is not being passed, yet I can return the date from the POST: echo $_SESSION['dateOpen']; this returns the date as 2014-06-01
I'm a bit of a noob, so any suggestions are welcome. Using postgresql database.
try {
$sql2 = "INSERT INTO excavation.contexts_spatial
(area_easting,
area_northing,
context_number,
open_date,
close_date,
excavation_method,
contamination,
zooarchaeology_comments,
ceramic_comments) VALUES (
:area_easting,
:area_northing,
:context_number,
:open_date,
:close_date,
:excavation_method,
:contamination,
:zooarchaeology_comments,
:ceramic_comments)";
$stmt2 = $conn->prepare($sql2);
// prepare sql and bind parameters
$stmt2->bindParam(':area_easting', $area_easting, PDO::PARAM_INT);
$stmt2->bindParam(':area_northing', $area_northing, PDO::PARAM_INT);
$stmt2->bindParam(':context_number', $nextContext, PDO::PARAM_INT);
$stmt2->bindParam(':open_date', $open_date, PDO::PARAM_STR);
$stmt2->bindParam(':close_date', $close_date, PDO::PARAM_STR);
$stmt2->bindParam(':excavation_method', $excavation_method, PDO::PARAM_STR);
$stmt2->bindParam(':contamination', $contamination, PDO::PARAM_STR);
$stmt2->bindParam(':zooarchaeology_comments', $excavation_method, PDO::PARAM_STR);
$stmt2->bindParam(':ceramic_comments', $excavation_method, PDO::PARAM_STR);
// insert a row
$area_easting = $_SESSION['area_easting'];
$area_northing = $_SESSION['area_northing'];
$nextContext = $_SESSION['nextContext'];
$open_date = $_SESSION['dateOpen'];
$close_date = $_SESSION['dateClose'];
$excavation_method = $_SESSION['excavationMethod'];
$contamination = $_SESSION['contamination'];
$zooarchaeology_comments = $_SESSION['zooarchaeologyComments'];
$ceramic_comments = $_SESSION['ceramicComments'];
$stmt2->execute();
echo "New records created successfully in contexts spatial<br />";
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
You are executing the query twice: Once before you assign your session variables to the parameters you have bound in the query and once after.
You need to remove the first $stmt2->execute(); statement.

Getting "Invalid parameter number" when updating database, why?

I'm trying to make my CMS be able to edit different fields (e.g. name). When I hit "Update", though, I get the following error:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens' in /studenthome.hallam.shu.ac.uk/STUDENTHOME10/1/b5035381/public_html/affinity/cms/process/editRecord.php: in /studenthome.hallam.shu.ac.uk/STUDENTHOME10/1/b5035381/public_html/affinity/cms/process/editRecord.php on line 28 PDOException: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens in /studenthome.hallam.shu.ac.uk/STUDENTHOME10/1/b5035381/public_html/affinity/cms/process/editRecord.php on line 28 Call Stack: 0.0029 659144 1. {main}() /studenthome.hallam.shu.ac.uk/STUDENTHOME10/1/b5035381/public_html/affinity/cms/process/editRecord.php:0 0.0135 672928 2. PDOStatement->execute() /studenthome.hallam.shu.ac.uk/STUDENTHOME10/1/b5035381/public_html/affinity/cms/process/editRecord.php:28
Here is my code:
<?php
ini_set('display_errors', 1);
// add your includes for connections and functions
// make sure the path is correct
require ('../../includes/conn.inc.php');
require ('../../includes/functions.inc.php');
// sanitize user variables
$splayerName = safeString($_POST['playerName']);
$splayerDescription = safeString($_POST['playerDescription']);
$splayerImage = safeString($_POST['playerImage']);
$splayerRank = safeString($_POST['playerRank']);
$splayerSpec = safeString($_POST['playerSpec']);
$splayerID = safeInt($_POST['playerID']);
// build prepare statement
$sql = "UPDATE affinity SET playerName = :playerName,
playerDescription = :playerDescription,
playerImage = :playerImage,
playerRank = :playerRank,
playerSpec = :playerSpec
WHERE playerID = :playerID";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':playerName', $splayerName, PDO::PARAM_STR);
$stmt->bindParam(':playerDescription', $splayerDescription, PDO::PARAM_STR);
$stmt->bindParam(':playerImage', $splayerImage, PDO::PARAM_STR);
$stmt->bindParam(':playerRank', $splayerRank, PDO::PARAM_STR);
$stmt->bindParam(':playerRank', $splayerRank, PDO::PARAM_STR);
$stmt->bindParam(':playerSpec', $splayerSpec, PDO::PARAM_INT);
$stmt->execute();
// redirect browser
header("Location: ../cms.php");
// make sure no other code executed
exit;
?>
I'm not sure why this isn't working; how can I fix it?
:playerRank
has been bound 2 times and
:playerID
Haven't been bound.
And :
:playerSpec
Should be bound as a string, not an int.
$stmt->bindParam(':playerName', $splayerName, PDO::PARAM_STR);
$stmt->bindParam(':playerDescription', $splayerDescription, PDO::PARAM_STR);
$stmt->bindParam(':playerImage', $splayerImage, PDO::PARAM_STR);
$stmt->bindParam(':playerRank', $splayerRank, PDO::PARAM_STR);
$stmt->bindParam(':playerSpec', $splayerSpec, PDO::PARAM_STR);
$stmt->bindParam(':playerID', $splayerID, PDO::PARAM_INT);
Where's your bind for playerID? That's whats causing it. You'e binding Rank twice and ID never, and they should be in order correct?
$stmt->bindParam(':playerName', $splayerName, PDO::PARAM_STR);
$stmt->bindParam(':playerDescription', $splayerDescription, PDO::PARAM_STR);
$stmt->bindParam(':playerImage', $splayerImage, PDO::PARAM_STR);
$stmt->bindParam(':playerRank', $splayerRank, PDO::PARAM_STR);
$stmt->bindParam(':playerSpec', $splayerSpec, PDO::PARAM_INT);
$stmt->bindParam(':playerID', $splayerID, PDO::PARAM_STR);
<?php
ini_set('display_errors', 1);
// add your includes for connections and functions
// make sure the path is correct
require ('../../includes/conn.inc.php');
require ('../../includes/functions.inc.php');
// sanitize user variables
$splayerName = safeString($_POST['playerName']);
$splayerDescription = safeString($_POST['playerDescription']);
$splayerImage = safeString($_POST['playerImage']);
$splayerRank = safeString($_POST['playerRank']);
$splayerSpec = safeString($_POST['playerSpec']);
$splayerID = safeInt($_POST['playerID']);
// build prepare statement
$sql = "UPDATE affinity SET playerName = :playerName,
playerDescription = :playerDescription,
playerImage = :playerImage,
playerRank = :playerRank,
playerSpec = :playerSpec
WHERE playerID = :playerID";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':playerName', $splayerName, PDO::PARAM_STR);
$stmt->bindParam(':playerDescription', $splayerDescription, PDO::PARAM_STR);
$stmt->bindParam(':playerImage', $splayerImage, PDO::PARAM_STR);
$stmt->bindParam(':playerRank', $splayerRank, PDO::PARAM_STR);
$stmt->bindParam(':playerSpec', $splayerSpec, PDO::PARAM_STR);
$stmt->bindParam(':playerID', $splayerID, PDO::PARAM_INT);
$stmt->execute();
// redirect browser
header("Location: ../cms.php");
// make sure no other code executed
exit;
?>

PHP MYSQL update syntax error

So I have a rather big form that is used to update the database. I am having trouble now with this block of code that inserts data from a form. Previously it was working but I changed the form to show "open" transactions so a user knows which transaction number to close. Now I get syntax/access violations. Rtransid is the key, if anyone was wondering. Thanks for any help.
//If there are any errors, display the form again. Otherwise, insert the data
if(!count($errors)){
$sql = "UPDATE repairorder SET
date = :date,
tech = :tech,
dispatcher = :dispatcher,
booth = :booth,
worktype = :worktype,
descript = :descript,
comment = :comment,
fstop = :fstop,
devtemp = :devtemp,
counter = :counter,
numstrips = :numstrips,
fserial = :fserial,
status = :status,
odate = :odate,
cdate = :cdate,
WHERE rtransid = :rtransid";
$stmt = $db->prepare($sql);
$stmt->bindParam(':rtransid', $_POST['rtransid'], PDO::PARAM_STR);
$stmt->bindParam(':date', $_POST['date'], PDO::PARAM_STR);
$stmt->bindParam(':tech', $_POST['tech'], PDO::PARAM_STR);
$stmt->bindParam(':dispatcher', $_POST['dispatcher'], PDO::PARAM_STR);
$stmt->bindParam(':booth', $_POST['booth'], PDO::PARAM_STR);
$stmt->bindParam(':worktype', $_POST['worktype'], PDO::PARAM_INT);
$stmt->bindParam(':descript', $_POST['descript'], PDO::PARAM_STR);
$stmt->bindParam(':comment', $_POST['$comment'], PDO::PARAM_STR);
$stmt->bindParam(':fstop', $_POST['fstop'], PDO::PARAM_STR);
$stmt->bindParam(':devtemp', $_POST['devtemp'], PDO::PARAM_STR);
$stmt->bindParam(':counter', $_POST['counter'], PDO::PARAM_STR);
$stmt->bindParam(':numstrips', $_POST['numstrips'], PDO::PARAM_STR);
$stmt->bindParam(':fserial', $_POST['fserial'], PDO::PARAM_STR);
$stmt->bindParam(':status', $_POST['status'], PDO::PARAM_STR);
$stmt->bindParam(':odate', $_POST['odate'], PDO::PARAM_STR);
$stmt->bindParam(':cdate', $_POST['cdate'], PDO::PARAM_INT);
//var_dump($stmt); //used for error control in dummy server
$stmt->execute();
}
If the error message looks like this You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE rtransid = ...' at line 1, you should update your query like so.
$sql = "UPDATE repairorder SET
date = :date,
tech = :tech,
dispatcher = :dispatcher,
booth = :booth,
worktype = :worktype,
descript = :descript,
comment = :comment,
fstop = :fstop,
devtemp = :devtemp,
counter = :counter,
numstrips = :numstrips,
fserial = :fserial,
status = :status,
odate = :odate,
cdate = :cdate
WHERE rtransid = :rtransid";
You probably miss the comma after :cdate

Call a stored procedure with the same name using PDO

I have two stored procedures in my database Postgres, both have the same name but the difference are the parameters.
procedure1(::string, ::integer, ::string, ::integer)
procedure1(::string, ::integer, ::integer)
In PDO doing bindParam correct, is coming STR, INT, INT but the prepere always performs procedure1.
How do I get him to understand what I call the procedure2?
Some information for more help? I clear? thanks
EDIT ===
...
$bounds = null; // forced for debug
if(!is_null($bounds)){
$query = "SELECT procedure1(:name, :domain, :geo, :userid)";
$stmt = $db->prepare($query);
$stmt->bindParam('name', $name, PDO::PARAM_STR);
$stmt->bindParam('domain', $idDomain, PDO::PARAM_INT);
$stmt->bindParam('geo', $geoString, PDO::PARAM_STR);
$stmt->bindParam('userid', $userId, PDO::PARAM_INT);
}else{
$query = "SELECT procedure1(:name, :domain, :userid)";
$stmt = $db->prepare($query);
$stmt->bindParam('name', $name, PDO::PARAM_STR);
$stmt->bindParam('domain', $idDomain, PDO::PARAM_INT);
$stmt->bindParam('userid', $userId, PDO::PARAM_INT);
}
$result = $stmt->execute();
...
The error it gives is that he is running a procedure that requires four parameters
Try changing your $query statements to explicitly tell PDO the types, and to avoid extra code switch to bindValue (PDO uses the PARAM flags to format SQL, not to cast data types):
$bounds = null; // forced for debug
if(!is_null($bounds)){
$query = "SELECT procedure1(:name::VARCHAR, :domain::INTEGER, :geo::VARCHAR, :userid::INTEGER)";
$stmt = $db->prepare($query);
$stmt->bindValue('name', $name);
$stmt->bindValue('domain', $idDomain);
$stmt->bindValue('geo', $geoString);
$stmt->bindValue('userid', $userId);
}else{
$query = "SELECT procedure1(:name::VARCHAR, :domain::INTEGER, :userid::INTEGER)";
$stmt = $db->prepare($query);
$stmt->bindValue('name', $name);
$stmt->bindValue('domain', $idDomain);
$stmt->bindValue('userid', $userId);
}
$result = $stmt->execute();

Categories