MySQL Insert using PDO in PHP [closed] - php

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I've been trying to get a form to insert records to a MySQL database using a form, but for some reason it errors out on me and I can't figure out why.
Here is the code that processes the request:
if ($_SERVER['REQUEST_METHOD']=='POST'){
// database connection
try {
$dbh = new PDO('mysql:host='.$host.';dbname='.$dbName, $dbUser, $dbPass);
$dbh -> setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$dbh -> exec("SET NAMES 'utf8'");
} catch (Exception $e) {
echo "Error!: " . $e->getMessage() . "<br/>";
die();
}
// new data
$title = $_POST["txtTitle"];
$description = $_POST["txtDesc"];
$content = $_POST["txtContent"];
$sql = "INSERT INTO tblPageContent
SET (PageTitle, Description, PageContent)
VALUES (:title, :desc, :content)";
try {
$update = $dbh->prepare($sql);
$update->bindParam(":title",$title, PDO::PARAM_STR);
$update->bindParam(":desc",$description, PDO::PARAM_STR);
$update->bindParam(":content",$content, PDO::PARAM_STR);
$update->execute();
$id = $update->dbh->lastInsertId();
$update->dbh->commit();
echo $id;
} catch (Exception $e) {
echo "Data could not be updated in the database.";
echo $e;
exit;
}
}
Whenever I try to use it, I end up with this:
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 '(PageTitle, Description, PageContent) VALUES
('Awards', 'This is a test', '' at line 2'
I've tried tweaking the SQL syntax, but I still can't get it to work. Is there something I'm missing here?

Your insert syntax is WRONG.
The correct syntax is:
insert into tblPageContent (pageTitle, Description, PageContent)
values (:title, :desc, :content)
I recommend you have MySQL reference manual at hand

In your SQL, take out the SET before the first (. You use SET in updates, not inserts.

Related

Unable to insert into two different tables with help of transactions [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
Below is a my code write up in which i am trying to insert data into two different tables with help of transactions but code is not executing. Trying very hard to find out issue but unable to resolve it.
I am getting this error: 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 ''u_id_fk','device_type','ip_num','package','pkg_id_fk') VALUES('79','abc','128.1' at line 1[]
$cust_name = 'multi';
$u_name = 'multi2';
$cnic_num = '421';
$address = 'sadaddd';
$password = md5('423423');
$cellnum='43243';
$p_id_fk=(int)'3';
try {
// First of all, let's begin a transaction
$conn->beginTransaction();
// If we arrive here, it means that no exception was thrown
// i.e. no query has failed, and we can commit the transaction
// Forgot to close the VALUES bracket and couldn't find your $email
$users_stmt=$conn->prepare("INSERT INTO users (`cust_name`, `u_name`, `cnic`, `address`, `password`, `email`) VALUES (:cust_name, :u_name, :cnic, :address, :password, :email)");
// PDO::execute() can accept an array of parameter bound to your query so you may avoid selecting data type when using bindParam()
$users_stmt->execute(["cust_name"=>$cust_name, "u_name"=>$u_name, "cnic"=>$cnic_num, "address"=>$address, "password"=>$password, "email"=>$email]);
// Not sure if $db is a PDO object...
$connections_stmt=$conn->prepare("INSERT INTO connections('u_id_fk','device_type','ip_num','package','pkg_id_fk') VALUES(:u_id_fk,:device_type,:ip_num,:package,:pkg_id_fk)");
$connections_stmt->execute(["u_id_fk"=>$u_id,"device_type"=>$device_type,"ip_num"=>$ip_num,"package"=>$package,"pkg_id_fk"=>$p_id_fk]);
$conn->commit();
} catch (Exception $e)
{
// An exception has been thrown
// We must rollback the transaction
$conn->rollback();
echo $e;
}
Please help to resolve it! Thanks
It is very important to set PDO error mode to EXCEPTION during connection.
Avoid using simple hashing algorithms for password as it can be extracted using Rainbow Attack.
$cust_name = 'multi';
$u_name = 'multi2';
$cnic_num = '421';
$address = 'sadaddd';
$password = md5('423423');
$cellnum='43243';
$p_id_fk=(int)'3';
try {
// DB vars
$db_host="";
$db_name="";
$db_username="";
$db_password="";
// Create a new PDO connection and set error mode to EXCEPTION
$conn=new PDO("mysql:host=".$db_host.";dbname=".$db_name,$db_username,$db_password,array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$conn->beginTransaction();
// Forgot to close the VALUES bracket and couldn't find your $email
$users_stmt=$conn->prepare("INSERT INTO users (`cust_name`, `u_name`, `cnic`, `address`, `password`, `email`) VALUES (:cust_name, :u_name, :cnic, :address, :password, :email)");
// PDO::execute() can accept an array of parameter bound to your query so you may avoid selecting data type when using bindParam()
$users_stmt->execute(["cust_name"=>$cust_name, "u_name"=>$u_name, "cnic"=>$cnic_num, "address"=>$address, "password"=>$password, "email"=>$email]);
$connections_stmt=$conn->prepare("INSERT INTO connections(`u_id_fk`,`device_type`,`ip_num`,`package`,`pkg_id_fk`) VALUES(:u_id_fk, :device_type, :ip_num, :package, :pkg_id_fk)");
$connections_stmt->execute(["u_id_fk"=>$u_id, "device_type"=>$device_type, "ip_num"=>$ip_num, "package"=>$package, "pkg_id_fk"=>$p_id_fk]);
$conn->commit();
} catch (Exception $e){
$conn->rollback();
echo $e->getMessage();
}
The closing double quotation in your first statement is not correct, it must be at the end of it and also you missed the end bracket of prepare function
$stmt=$conn->prepare("INSERT INTO users (cust_name, u_name,cnic,address,password,email) VALUES (?, ?, ?, ?, ?, ?)");
Try to correct that typo.

Php and mysql weird error with select [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I'm a beginner in web design and I have this problem. I'm trying to create a login page but when I try to create the login it throws a error as follows:
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 ':username and passwordhash=:passwordhashed)' at line 1
With php code of
Try {
// $SQL = 'INSERT INTO Passwords (username, password, passwordhashed) VALUES (:username,:password,:passwordhashed);';
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
$PasswordHashed = sha1($password);
echo "Username: ". $username ."<br> Password: ". $password . "<br> PasswordHashed: " . $PasswordHashed;
$SQL = null;
$SQL = "SELECT * FROM BlaBla WHERE (username=:username and passwordhash=:passwordhashed);";
$Statement = $MySQL->prepare($SQL);
$Statement->bindValue(':username', $username);
$Statement->bindValue(':passwordhashed', $PasswordHashed);
$Statement->execute();
$Statement = $MySQL->query($SQL);
if ($Statement->rowCount() < 1 ) {
echo 'NOPE';
} else {
echo 'welcome back '. $username;
}
} catch(PDOException $e) {
$ErrorTitle = 'Error';
$Error = "error writing to database";
$ErrorInfo = '<p>Please contact administrator at stephan.littel#stecasso.nl</p> <br> <p>'. $e->getMessage() . '</p>';
include './HTML/Error.php';
exit();
}
I don't know what the error is. Could anyone help me?
Here:
$Statement = $MySQL->prepare($SQL);
^---your prepared statement
$Statement->bindValue(':username', $username);
$Statement->bindValue(':passwordhashed', $PasswordHashed);
$Statement->execute();
$Statement = $MySQL->query($SQL);
^----raw queries have no placeholders
You prepare a statement, and execute it. But then you do a RAW query with the same SQL, replacing the result of the prepared version. You cannot use placeholders in a raw query like that. Hence your error.
That final ->query() call is useless and redundant.
Found the problem. Problem was I used query and execute. My fault of slopy bug tracking.

Error when using PHP to modify database [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I'm trying to insert a bunch of data into a database, but I am having this error:
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 '0' at line 1
Here are my two files:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert new Page</title>
</head>
<body>
<form action="insert_page.php" method="get">
New Page Name:<br>
<input type="text" name="pagename">
<input type="submit" value="Insert" >
</form>
</body>
</html>
This is insert_page.html, it's simply a text box and a button where the user can choose the new name for a new page to be entered in the database.
Now, here's the PHP being called when the button is pressed
<?php
$servername = "db.ist.utl.pt";
$username = "ist178349";
$password = "getrekt";
$dbname = "ist178349";
$pagename = $_POST['pagename'];
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO pagina (userid, pagecounter, nome, idseq, ativa)
VALUES (78349, 95002, " + $pagename + ",1151988, true)";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
However, I am getting that error, which I can't really understand. Any suggestions? Thanks in advance.
You should fix your query that contains + use . or leave it out and use single quote, that's acceptable in PHP sql query string.
$sql = "INSERT INTO pagina (userid, pagecounter, nome, idseq, ativa)
VALUES (78349, 95002, '$pagename', 1151988, true)";

Can't figure out what's wrong with my SQL syntax [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm running the following SQL query in PHP
try {
$sql = "INSERT INTO doc SET type = 1,
candID = :candID,
userID = ".$_SESSION['userid'].",
filename = ".$_FILES['file']['tmp_name'].",
date=date_format(curdate(), '%d/%m/%Y')";
$s = $pdo->prepare($sql);
$s->bindValue(':candID', $_POST['candid']);
$s->execute();
}
catch (PDOException $e) {
$error = 'Error adding doc: ' . $e->getMessage();
include $errorpage;
exit();
}
And I'm getting the following error:
Error adding doc: 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 ':\xampp\tmp\phpD58B.tmp, date=date_format(curdate(),
'%d/%m/%Y')' at line 5
I can't quite figure out why I'm getting this error. Is there something wrong with my syntax that I'm missing?
filename = ".$_FILES['file']['tmp_name'].", should be filename = '".$_FILES['file']['tmp_name']."',
so the code should look like
try {
$sql = "INSERT INTO doc SET type = 1,
candID = :candID,
userID = ".$_SESSION['userid'].",
filename = '".$_FILES['file']['tmp_name']."',
date=date_format(curdate(), '%d/%m/%Y')";
$s = $pdo->prepare($sql);
$s->bindValue(':candID', $_POST['candid']);
$s->execute();
}
catch (PDOException $e) {
$error = 'Error adding doc: ' . $e->getMessage();
include $errorpage;
exit();
}
SET is used for UPDATE statements.
$sql = "INSERT INTO doc (type, candID, userID, finame, date) VALUES (1, :candID, :userID, :filename, :date)";
$s = $pdo->prepare($sql);
$s->execute(array(':candID' => $_POST['candid'], ':userID' => $_SESSION['userid'], ':filename' => $_FILES['file']['tmp_name'], ':date' => date('d/m/Y'));

Invalid parameter in PDO SQL query [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm getting a strange error with PDO:{"error":{"text":SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens}}
I tried this sql query and i didn't find,if someone could help me;
My code:
$sql = "UPDATE feeds SET status=:statuschosen WHERE idUser=:id AND id:idfeed";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("statuschosen", $post->statuschosen);
$stmt->bindParam("idfeed", $post->idfeed);
$stmt->bindParam("id", $id);
$stmt->execute();
$db = null;
echo json_encode($post);
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
My table have this structure:
id URL idUser status
Thank you for your help!!!
You were missing an equal sign in your $sql string. Also while binding the params you have used wrong placeholders,See below:
$sql = "UPDATE feeds SET status=:statuschosen WHERE idUser=:id AND id=:idfeed";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam(":statuschosen", $post->statuschosen);
$stmt->bindParam(":idfeed", $post->idfeed);
$stmt->bindParam(":id", $id);
$stmt->execute();
$db = null;
echo json_encode($post);
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}

Categories