I'm trying to use PDO to insert data into my database but I'm getting this error
Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1 in C:\xampp\htdocs\pfe\users\execute.php:21 Stack trace: #0 C:\xampp\htdocs\pfe\users\execute.php(21): PDOStatement->execute() #1 {main} thrown in C:\xampp\htdocs\pfe\users\execute.php on line 21'
this is my code :
<?php
session_start();
require_once("database.php");
$req = $dbh ->prepare('INSERT INTO idad
(etat, description, image, localisation,
statut, categorie, author_num, created_at)
VALUES(:etat, :description, :image, :localisation,
:statut, :categorie, :author_num, NOW() ');
$req ->bindParam(':etat' , $_POST["etat"]);
$req ->bindParam(":description" , $_POST["description"]);
$req ->bindParam(":image" , $_POST["image"]);
$req ->bindParam(":localisation" , $_POST["localisation"]);
$req ->bindParam(":statut" , $config['STATUS'][0]);
$req ->bindParam(":categorie" , $_POST["categorie"]);
$req ->bindParam(":author_num" , $_SESSION["id"]);
$req ->execute();
var_dump($_POST);
var_dump($_SESSION);
var_dump($config);
?>
Instead of having multiple lines of bindParam, did you try :
$req -> execute(array(
':param1' => $my_param1,
':param2' => $my_param2,
':param3' => $my_param3,
));
I'm not sure your solution work or not, it's just I always did it my way because got recommended to do it this way, for security purposes if I'm right (still learning).
Also my code may be clearer and if I'm right about it, your code doesn't verify your $_POST variables aren't undefined nor empty so maybe it will lead to problems one day.
Related
I'm trying to do a form to insert values on a data base, but it's not working.
In fact, I used to use a VM that is now dead. And when I switched to Xammp my program didn't work anymore.
$titre = $_POST["titre"];
$categorie = $_POST["categorie"];
$portion = $_POST["portion"];
$heure_cuiss = $_POST["heure_cuiss"];
$minute_cuiss = $_POST["minute_cuiss"];
$heure_prepa = $_POST["heure_prepa"];
$minute_prepa = $_POST["minute_prepa"];
$heure_rep = $_POST["heure_rep"];
$minute_rep = $_POST["minute_rep"];
$cuiss = $_POST["cuiss"];
$cost = $_POST["cost"];
$dif = $_POST["dif"];
$histoire = $_POST["histoire"];
$region = $_POST["region"];
$temps = intval($heure_cuiss) + intval($minute_cuiss)/60 + intval($heure_prepa) + intval($minute_prepa)/60 + intval($heure_rep) + intval($minute_rep)/60;
$query = $bdd -> prepare('INSERT INTO recette (titre, categorie, portion, heure_cuiss, minute_cuiss, heure_prepa, minute_prepa, heure_rep, minute_rep , cuiss, cost, dif, histoire, region, temps)
VALUES(:titre, :categorie, :portion, :heure_cuiss, :minute_cuiss, :heure_prepa, :minute_prepa, :heure_rep, :minute_rep, :cuiss, :cost, :dif, :histoire, :region, :temps)');
$query -> execute(array('titre'=>$titre, 'categorie'=>$categorie, 'portion'=>$portion, 'heure_cuiss'=>$heure_cuiss, 'minute_cuiss'=>$minute_cuiss, 'heure_prepa'=>$heure_prepa, 'minute_prepa'=>$minute_prepa, 'heure_rep'=>$heure_rep, 'minute_rep'=>$minute_rep, 'cuiss'=>$cuiss, 'cost'=>$cost, 'dif'=>$dif, 'histoire'=>$histoire, 'region'=>$region, 'temps'=>intval($temps)));
I get this error
Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'portion, heure_cuiss, minute_cuiss, heure_prepa, minute_prepa, heure_rep, min...' at line 1 in C:\xampp\htdocs\ptut\upload\back-index.php:46 Stack trace: #0 C:\xampp\htdocs\ptut\upload\back-index.php(46): PDOStatement->execute(Array) #1 {main} thrown in C:\xampp\htdocs\ptut\upload\back-index.php on line 46
I've tried to rewrite my database, to write my insert with '?' but nothing works.
I've been working on this problem for 5 hours. I really need your help !
Thanks, Thomas
Make sure your password is empty like this :
$bdd = new PDO('mysql:host=localhost;dbname=yourDataBase', 'root', '');
I want to add data to my table with stored procedure, but I have this error:
Gönder
Fatal 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 MariaDB server version for the right syntax to use near 'Teknoloji,V,,1)' at line 1' in C:\xampp\htdocs\berat\isyerikayit.php:142 Stack trace: #0 C:\xampp\htdocs\berat\isyerikayit.php(142): PDO->query('CALL isyerikayi...', 2) #1 {main} thrown in C:\xampp\htdocs\berat\isyerikayit.php on line 142
<?php
if (isset($_POST['gonder']))
{
$adi = $_POST["adi"];
$calismaturu = $_POST["calismaturu"];
$iscigucu = $_POST["iscigucu"];
$hizmetturu = $_POST["hizmetturu"];
$butce = $_POST["butce"];
if($calismaturu == 'V')
{
$sorgu= $db->query("CALL isyerikayitV($adi,$calismaturu,$iscigucu,$hizmetturu)",PDO::FETCH_ASSOC);
echo '<script>alert("Hizmet Veren Firma Eklendi.");</script>';
}
else
{
$sorgu= $db->query("CALL isyerikayitE($adi,$calismaturu,$butce)",PDO::FETCH_ASSOC);
echo '<script>alert("Hizmet Edilen Firma Eklendi.");</script>';
}
}
?>
My isyerikayitE() and isyerikayitV procedures are 7.
It seems that $iscigucu is empty:
"that corresponds to your MariaDB server version for the right syntax to use near 'Teknoloji,V,,1)'"
And all your string variables are missing the quotes:
A quick solution is to do:
$iscigucu = empty($_POST["iscigucu"]) ? "''" : "'".$_POST["iscigucu"]."'";
for each one of them.
or
$iscigucu = "'".$iscigucu."'"
But the right way to solve this is to use prepared statements:
$call = mysqli_prepare($mysqli, 'CALL test_proc(?, ?, ?, ?)');
mysqli_stmt_bind_param($call, 'ssss', $adi,$calismaturu,$iscigucu,$hizmetturu);
mysqli_stmt_execute($call);
Take a look at: http://php.net/manual/en/mysqli-stmt.bind-param.php
I'm really puzzled by error that comes from my simple insert. I've checked the syntax many times by different checkers and searched for similar troubles but haven't found solution.
The Error looks like this:
'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 near ' , , , , , , , , , , , , , , )' at line 1' in
And my code is basically this:
$yhteys = new PDO('mysql:host=localhost;dbname=XXXX', 'YYYY', 'ZZZZ');
$kysely = $yhteys->prepare("INSERT INTO hakija (Kutsumanimi, Etunimet, Sukunimi, SyntymAika, Syntymapaikka, Sahkoposti, Puhelinnumero, Postiosoite, Postinumero, Postitoimipaikka, Maa, Suosittelija, IPos, Lahetysaika, Vapaa_sana, Sosme) VALUES ($nimi, $etunimet, $sukunimi, $saika, $spaikka, $email, $puhelin, $osoite, $postinro, $postitmp, $maa, $suosittelija, $IPos, $lahetysaika, $vapaasana, $sosme)");
$kysely->execute();
If I use this INSERT directly via phpMyAdmin, it works, but from php.. Can anyone help me out?
PHP: native (5.4)
MySQL 5.6
You should use prepared statements. It will prevent sql injections and you wont have to deal with variables types
$yhteys = $dbh->prepare("INSERT INTO hakija (Kutsumanimi, Etunimet,...) VALUES (:kutsumanimi, :ktunimet, ...)");
$yhteys ->bindParam(':kutsumanimi', $kutsumanimi);
$yhteys ->bindParam(':ktunimet', $ktunimet);
...
$yhteys ->execute();
Have a look here : http://php.net/manual/en/pdo.prepared-statements.php
If values you are inserting are Strings you need to enclose it in quotes
$kysely = $yhteys->prepare("INSERT INTO hakija (Kutsumanimi, Etunimet, Sukunimi, SyntymAika, Syntymapaikka, Sahkoposti, Puhelinnumero, Postiosoite, Postinumero, Postitoimipaikka, Maa, Suosittelija, IPos, Lahetysaika, Vapaa_sana, Sosme) VALUES ('$nimi', '$etunimet', '$sukunimi', '$saika', '$spaikka', '$email', '$puhelin', '$osoite', '$postinro', '$postitmp', '$maa', '$suosittelija', '$IPos', '$lahetysaika', '$vapaasana', '$sosme')");
if values are integer you can skip quotes
I am inserting the values using PDO but i am getting error as:
Fatal 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 near 'desc,price,nick_name,gender,size,color,birth_date,uname,uphone,ucountry,ustate,u' at line 1' in C:\wamp\www\aa\abc.php:58 Stack trace: #0 C:\wamp\www\www\aa\abc.phpphp(58): PDOStatement->execute(Array) #1 {main} thrown in C:\wamp\www\www\aa\abc.php.php on line 58
also getting Warning: implode() [function.implode]: Bad arguments for implode function
Code:
foreach ($_POST['pcheck'] as $p_check) ////storing checkbox values
{
$pcheckp[] = $p_check;
} $finalcheck = implode(',', $pcheck);
foreach ($_POST['pinc'] as $p_inc) ////storing inputfield values
{
$pinc[] = $p_inc;
} $finalpinc = implode(',', $pinc);
$sql = "INSERT INTO list (u_id,list_type,list_ff,breed,title,desc,price,nick_name,gender,size,color,birth_date,uname,uphone,ucountry,ustate,ucity,usite,pcheck,pinc,photo)
VALUES(:uid,:list_type,:list_ff,:breed,:title,:desc,:price,:nick_name,:gender,:size,:color,:date,:uname,:uphone,:ucountry,:ustate,:ucity,:usite,:pcheck,:pinc,:p_photo)";
$q = $db->prepare($sql);
$q->execute(array(':uid'=>dd,
':list_type'=>$list_type,
':breed'=>$breed,
':title'=>$title,
':desc'=>$desc,
':price'=>$price,
':list_ff'=>$list_ff,
':nick_name'=>$nick_name,
':gender'=>$gender,
':size'=>$size,
':color'=>$color,
':date'=>$date,
':uname'=>$uname,
':uphone'=>$uphone,
':ucountry'=>$ucountry,
':ustate'=>$ustate,
':ucity'=>$ucity,
':usite'=>$usite,
':pcheck'=>$finalcheck,
':pinc'=>$finalpinc,
':p_photo'=>$p_photo));
$_POST['pcheck'] and $_POST['pinc'] is used to get checkbox and input values which i am going to store in column in mysql.
I have checked many times to find the syntax error in insert query but nothing wrong is in it
Hoping to get help
Thanks!
for Warning: implode()
$finalcheck = implode(',', $pcheck);
should be
$finalcheck = implode(',', $pcheckp);
also desc is reserved for mysql you need to use it with `
$sql = "INSERT INTO list (`u_id`,`list_type`,`list_ff`,`breed`,`title`,`desc`,`price`,`nick_name`,`gender`,`size`,`color`,`birth_date`,`uname`,`uphone`,`ucountry`,`ustate`,`ucity`,`usite`,`pcheck`,`pinc`,`photo`)
VALUES(:uid,:list_type,:list_ff,:breed,:title,:desc,:price,:nick_name,:gender,:size,:color,:date,:uname,:uphone,:ucountry,:ustate,:ucity,:usite,:pcheck,:pinc,:p_photo)";
I have a php script to update details in a MySQL table. It all worked fine but now I have changed the db connection method to PDO:
$pdo = new PDO('mysql:host=localhost;dbname=****', '****', '*****');
I made various changes to the script to accommodate this so it continues to work, The only place that fails is right at the end after the mysql table has been updated. I get this error:
Fatal 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 near 'and park_id=31' at line 1' in /home3/danville/public_html/test2/index.php:29 Stack trace: #0 /home3/danville/public_html/test2/index.php(29): PDO->query('update tpf_ride...') #1 {main} thrown in /home3/danville/public_html/test2/index.php on line 29
This is the piece of code causing the error:
$query = "update tpf_rides set name='$name',type='$type'";
if($topride!=""){$query .= ",top_ride=$topride";}
if($info!=""){$query .= ",info='$info'";}
if($height!=""){$query .= ",height=$height";}
if($length!=""){$query .= ",length=$length";}
if($speed!=""){$query .= ",speed=$speed";}
if($inversions!=""){$query .= ",inversions=$inversions";}
$query .= " where ride_id=".$ride_id." and park_id=".$park_id;
$pdo->query($query);
}
line 29 is this on Notepad++ $pdo->query($query); although the error message seems to reference the line above that $query .= " where ride_id=".$ride_id." and park_id=".$park_id;
Any ideas what I ned to change to stop the error? Additional details - I connect to the db with a require_once include. The updates do take effect despite the error.
If you're going to switch to PDO, you might as well take advantage of prepared statements and parameter binding. It actually makes your queries much safer from SQL injection and also makes your code more readable. Your query builder approach does complicate things a little but it's still possible. I'd also highly recommend enabling error reporting during development. For example
error_reporting(E_ALL);
ini_set('display_errors', 'On');
$upd = array('name = :name', 'type = :type');
$values = array(
'name' => $name,
'type' => $type,
'ride_id' => $ride_id,
'park_id' => $park_id
);
if (!empty($topride)) {
$upd[] = 'top_ride = :topride'; // :topride is the named parameter placeholder
$values['topride'] = $topride; // the array key matches the named placeholder above
}
if (!empty($info)) {
$upd[] = 'info = :info';
$values['info'] = $info;
}
// and so on
$query = sprintf('UPDATE tpf_rides SET %s WHERE ride_id = :ride_id AND park_id = :park_id',
implode(', ', $upd));
$stmt = $pdo->prepare($query);
$stmt->execute($values);