I am trying to insert some data into postgres database using pdo connection in php. Connection is successful, but insert query is giving error in syntax, i cant figure it out what is the fault in my syntax.
$dbcon->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$id = "12345";
$name = "Sueaj Roy";
$fname = "Biplab Roy";
$aadhaar = "5678973";
$dob = "22/12/90";
$statement = $dbcon->prepare("INSERT INTO user (full_name, father_name, dob, aadhaar_no, id) VALUES (:A,:B,:C,:D,:E)");
$statement->bindValue(':A', $name);
$statement->bindParam(':B', $fname);
$statement->bindParam(':C', $dob);
$statement->bindParam(':D', $aadhaar);
$statement->bindParam(':E', $id);
$statement->execute();
my table
user is a reserved word in Postgres. If you name any object user you have to enclose the name in double quotes to address it.
INSERT INTO "user"
...
Related
PDO noob here!
I had tried this script with a sqlite file and it works perfectly, but not I have switched to a mysql database and it gives problem, without entering the data into the database.
(_db.php file)
$dsn = 'mysql:dbname=prova_schedule;host=127.0.0.1';
$user = 'root';
$password = '';
$db = new PDO($dsn, $user, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
(insert.php)
<?php
require_once '_db.php';
$insert = "INSERT INTO events (name, start, end) VALUES (:name, :start, :end)";
$stmt = $db->prepare($insert);
$stmt->bindParam(':start', $_POST['start']);
$stmt->bindParam(':end', $_POST['end']);
$stmt->bindParam(':name', $_POST['name']);
$stmt->execute();
class Result {}
$response = new Result();
$response->result = 'OK';
$response->message = 'Created with id: '.$db->lastInsertId();
header('Content-Type: application/json');
echo json_encode($response);
?>
Sincerly I have no idea why it's not working anymore properly with a mysql database.
Thank you for your help!
The word "events" is a reserved word in at least 1 version of MySQL so you'll need to put back-ticks around it so that it looks like:
`events`
The MySQL website has a section where you can look up what words are reserved words for a given version of MySQL.
I am doing an insert on the MySQL table "analytics" with the fields "a_id" (PRIMARY and UNIQUE), "a_query" and "a_date".
My code:
function queryanalytics($clsendquery) {
$datetime = date("Y-m-d H:i:s");
$connection = connectsql();
$sql = "INSERT INTO analytics (a_query,a_date) VALUES (?,?)";
$stmt = $connection->prepare($sql);
$stmt->bind_param('ss',$clsendquery,$datetime);
$stmt->execute;
$stmt->close();
}
Nothing updates in the database and $stmt->affected_rows returns 0.
There are no errors in $stmt->error or $connection->error.
When I run the insert in phpMyAdmin it works fine.
I have other selects and inserts that work fine with the same connection, why does this one not?
Please help me.
$stmt->execute; should be $stmt->execute();
This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 2 years ago.
I'm attempting to insert some data into a table using mysqli functions.
My connection works fine using the following:
function connectDB(){
// configuration
$dbuser = "root";
$dbpass = "";
// Create connection
$con=mysqli_connect("localhost",$dbuser,$dbpass,"my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
return false;
}else{
echo '<br />successfully connected<br />';
return $con;
}
}
But when I attempt to run my insert function I get nothing in the database.
function newUserInsertDB($name,$email,$password){
$con = connectDB();
// Prepare password
$password = hashEncrypt($password);
echo $password . "<br />";
// Perform queries
mysqli_query($con,"SELECT * FROM users");
mysqli_query($con,"INSERT INTO users (name,email,password,isActivated) VALUES ($name,$email,$password,0)");
// insert
mysqli_close($con);
}
I have been looking through the list of mysqli functions for the correct way to give errors but they all seem to be regarding the connection to the DB, not regarding success of an insert (and I can clearly see in my DB that it is not inserting.)
What would be the best way to debug? Which error handling shall I use for my insert?
I've tried using mysqli_sqlstate which gives a response of 42000 but I cannot see any syntax errors in my statement.
As mentioned in my comment, you would be better off using a prepared statement. For example...
$stmt = $con->prepare(
'INSERT INTO users (name, email, password, isActivated) VALUES (?, ?, ?, 0)');
$stmt->bind_param('sss', $name, $email, $password);
$stmt->execute();
Using this, you don't have to worry about escaping values or providing quotes for string types.
All in all, prepared statements are much easier and much safer than attempting to interpolate values into an SQL string.
I'd also advise you to pass the $con variable into your function instead of creating it within. For example...
function newUserInsertDB(mysqli $con, $name, $email, $password) {
// Prepare password
$password = hashEncrypt($password);
// functions that "echo" can cause unwanted side effects
//echo $password . "<br />";
// Perform queries
$stmt = $con->prepare(
'INSERT INTO users (name, email, password, isActivated) VALUES (?, ?, ?, 0)');
$stmt->bind_param('sss', $name, $email, $password);
return $stmt->execute(); // returns TRUE or FALSE based on the success of the query
}
The quotes are missing from the mysql statement from around the values. Also, you should escape the values before inserting them into the query. Do this way:
mysqli_query($con,"INSERT INTO users (name,email,password,isActivated) VALUES ('".
mysqli_real_escape_string($con,$name)."','".
mysqli_real_escape_string($con,$email)."','".
mysqli_real_escape_string($con,$password)."',0)");
Regards
I have using PHP for inserting integer value in Database.
Iam using like this
$postcode = $_POST['postcode'];
$mysql_user_resultset = mysqli_query($con, "INSERT into user (postcode) VALUES ($postcode)");
I have several field in DB. like name, username, etc. all are defined as varchar, but postcode only defined as int. If not enter the value for postcode, it doesn't insert into database
You could simply cast your variable into int:
$postcode = (int) $_POST['postcode'];
$mysql_user_resultset = mysqli_query($con, "INSERT into user (postcode) VALUES ($postcode)");
Note that you're not using any precautions regarding SQL injections, I would suggest you to bind your parameters before query them, using PDO class.
Convert $_POST['postcode'] to int, using
$postcode = (int)$_POST['postcode'];
Use PDO or sprintf for formatting mysql query:
sprintf example:
$mysql_user_resultset = mysqli_query($con, sprintf(
"INSERT into user (postcode) VALUES (%d)",
$_POST['postcode']));
PDO example:
$st = $db->prepare("INSERT into vendors user (postcode) VALUES (:postcode)");
$st->bindParam(':postcode', $_POST['postcode'], PDO::PARAM_INT);
$mysql_user_resultset = $st->execute();
I am trying to run an sql query using PDO prepared statements
$sql = "INSERT INTO tickets (ticketnumber, status) VALUES (1234, Open) ";
$stmt = $connection->prepare($sql);
$stmt->execute();
But it is just not inserting. What have I done wrong?
Here is my connection:
$host = "localhost";
$db_name = "";
$username = "";
$password = "";
$connection = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
Try this. It's much more secure.
Make sure you have included your connection file.
EDITED
$sql = "INSERT INTO `tickets` (ticketnumber, status) VALUES (:ticketnumber, :status)";
$stmt = $connection->prepare($sql);
$stmt->bindValue(':ticketnumber', 1234, PDO::PARAM_INT);
$stmt->bindValue(':status', 'Open', PDO::PARAM_STR);
$stmt->execute();
Also, the named parameters used above must NOT be enclosed in quotes. If you do so, it'll be treated as a literal string and not a named parameter.
You need to use quotes on strings before inserting them into a database.
Why use prepare if you're not preparing your data before sending it to the database?