PHP insert not working when using the ' symbol - php

I'm trying to insert some text into my database using mysqli trough PHP.
My insert statement is as follows:
$userID="1";
$description="Hi! It's been a while..."; //For example...
$sql = "INSERT INTO projecten (user_ref, description)
VALUES ('$userID','$description')";
if ($conn->query($sql) === TRUE) {
//redirect to right page
} else {
//error message...
}
The problem:
I always get an error message saying that there is something not right in my sql syntax near " 'ts been " Now I tried removing the ' symbol and then the code works, but I need to be able to let my users type what they want to type...
Does somebody know what I can do about this?
Thanks in advance!

Use bind_param It will handle all those string and prevent you form sql injection
$userID = "1";
$description = "Hi! It's been a while..."; //For example...
$stmt = $conn->prepare("INSERT INTO projecten (`user_ref`, `description`) VALUES (?, ?)");
$stmt->bind_param('is', $userID, $description);
/* execute prepared statement */
$stmt->execute();
printf("%d Row inserted.\n", $stmt->affected_rows);
/* close statement and connection */
$stmt->close();

Related

Get last inserted ID in prepared statement

I need to get the last inserted ID for each insert operation and put it into array, I am trying to see what is the correct way of doing it.
Following this post Which is correct way to get last inserted id in mysqli prepared statements procedural style?
I have tried to apply it to my code but I am still not getting the right response.
if($data->edit_flag == 'ADDED')
{
$rowdata[0] = $data->location_name;
$rowdata[1] = 0;
$rowdata[2] = $data->store_id;
$query = "INSERT IGNORE INTO store_locations (location_name,total_items, store_id) VALUES (?,?,?)";
$statement = $conn->prepare($query);
$statement->execute($rowdata);
$id = mysqli_stmt_insert_id($statement);
echo "inserted id: " . $id;
}
I then realised that I am using a PDO connection so obviously mysqli functions wont work. I went ahead and tried the following
$id = $conn->lastInsertId();
echo "insert id: " . $id;
but the response is still empty? What am I doing incorrectly? For the lastInsertId(), should I be using $conn or $statement from here:
$statement = $conn->prepare($query);
$statement->execute($rowdata);
You are using lastInsertId() correctly according to the PDO:lastInsertId() documentation
$statement = $conn->prepare($query);
$statement->execute($rowdata);
$id = $conn->lastInsertId();
Some potential reasons why it is not working:
Is this code within a TRANSACTION? If so, you need to COMMIT the transaction after the execute and before the lastInsertId()
Since you INSERT IGNORE there is the potential that the INSERT statement is generating an error and not inserting a row so lastInsertId() could potentially be empty.
Hope this helps!
If you are using pdo,
$stmt = $db->prepare("...");
$stmt->execute();
$lastInsId = $db->lastInsertId();

PHP PDO prepare transaction statement (Two inserts)

I have tried to insert two insert intos through a transaction statement but it did not work. The console is giving me database errors. I have checked the documentation http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers and it is obvious I am missing something.
The goal is simply insert into two different tables different information. I tried the following:
// create record
function create(){
try {
$stmt->beginTransaction();
$query = "INSERT INTO " . $this->table_name . "
SET user_id = ?, ";
// prepare query statement
$stmt = $this->conn->prepare($query);
// bind values to be inserted
$stmt->bindParam(1, $this->user_id);
$stmt->execute();
$query2 = "INSERT INTO legalcases_report
SET user_id = ?, ";
// prepare query statement 2
$stmt = $this->conn->prepare($query2);
$stmt->bindParam(1, $this->user_id);
$stmt->execute();
$stmt->commit();
return true;
} catch (Exception) {
$stmt->rollBack();
return false;
}
}
There are lots of problems in this code, I hope I can catch them all
// create record
function create(){
try {
// transaction work on a connection and not a statement
//$stmt->beginTransaction();
$this->conn->beginTransaction();
// Incorrect syntax for an INSERT command
// Error - Trailing comma in sytax
$query = "INSERT INTO " . $this->table_name . "
SET user_id = ?, ";
// prepare query statement
$stmt = $this->conn->prepare($query);
// bind values to be inserted
$stmt->bindParam(1, $this->user_id);
$stmt->execute();
// Incorrect syntax for an INSERT command
// Error - Trailing comma in sytax
$query2 = "INSERT INTO legalcases_report
SET user_id = ?, ";
// prepare query statement 2
$stmt = $this->conn->prepare($query2);
$stmt->bindParam(1, $this->user_id);
$stmt->execute();
// commit also works on a connection object
//$stmt->commit();
$this->conn->commit();
return true;
// PDO generates a PDOException so you should really catch that,
// it will fallback to the parent Exception object, BUT
// there may be times when you want to catch them seperately
// from the same try block, so use the correct one or both
} catch (PDOException $pex) {
$this->con->rollback();
$pex->getMessage();
exit; // because you have a serious problem
// or throw your own exception to the calling code
throw new Exception('Create user failed ' . $pex->getMessage());
}
}
Incorrect syntax for an INSERT command
The PHP PDO manual
I guess you should use PDO object, not PDOStatement:
try {
$this->conn->beginTransaction();
...
$this->conn->commit();

MySQLi insert, successful database connection but not successfully inserted [duplicate]

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

Which is correct way to get last inserted id in mysqli prepared statements procedural style?

i am using mysqli prepared statement to insert record in the table like this
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'world');
/* check connection */
if (!$link) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = mysqli_prepare($link, "INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($stmt, 'sssd', $code, $language, $official, $percent);
$code = 'DEU';
$language = 'Bavarian';
$official = "F";
$percent = 11.2;
/* execute prepared statement */
mysqli_stmt_execute($stmt);
if(mysqli_stmt_affected_rows($stmt) > 0){
//if insert is successful then get the insrted id.
}
/* close statement and connection */
mysqli_stmt_close($stmt);
/* close connection */
mysqli_close($link);
and would like to get the last inserted id , as the table has record_num field which is auto increment .
so my question is should i place connection name or the statement name inside the function.
i.e
1)
echo mysqli_insert_id($link);
Source: http://php.net/manual/en/mysqli.insert-id.php
2)
echo mysqli_stmt_insert_id($stmt);
Source: http://php.net/manual/en/mysqli-stmt.insert-id.php
which one is correct ?
which one will give me last insrted id by the $stmt ?
there are no other inserts are being done using the same stmt one the same page..*
Update:
according to the note from http://php.net/manual/en/mysqli-stmt.insert-id.php
I am doing only single insert so i guess i can use
mysqli_stmt_insert_id($stmt)
but while doing multiple inserts using prepared statements using
echo mysqli_insert_id($link);
is best practice.
You should use
mysqli_insert_id($link);
Because of this note on the PHP manual you referred us to
mysqli_stmt_insert_id
It should be noted that using mysqli_stmt->insert_id will not result in a unique ID being returned for each execution of a prepared insert statement. In practice, it appears that the first insertion ID is returned. If you are performing multiple inserts with the same prepared statement (one invocation of mysqli_stmt::prepare and multiple invocations of mysqli_stmt::execute() for a given statement), and need to keep the unique ID for each insert, use mysqli_connection->insert_id.
for procedural language you need to use below code,
mysqli_insert_id($link));
yes as you mention in 1 point.
Correct is 1) - link, as stated in documentation:
http://php.net/manual/en/mysqli.insert-id.php

mysqli INSERT anomaly

I have the following table:
ID: bigint autoinc
NAME: varchar(255)
DESCRIPTION: text
ENTRYDATE: date
I am trying to insert a row into the table. It executes without error but nothing gets inserted in database.
try {
$query = "INSERT INTO mytable (NAME, DESCRIPTION, ENTRYDATE) VALUES(?,?,?)";
$stmt = $conn->prepare($query);
$name= 'something';
$desc = 'something';
$curdate = "CURDATE()";
$stmt->bind_param("sss", $name, $desc, $curdate);
$stmt->execute();
$stmt->close();
$conn->close();
//redirect to success page
}
catch(Exception $e) {
print $e;
}
It runs fine and redirects to success page but nothing can be found inside the table. Why isn't it working?
What about replacing DESCTIPTION with DESCRIPTION inside the $query?
Edit
Just out of curiosity, I created a table called mytable and copy-pasted your code into a PHP script.
Here everything worked fine and rows got inserted, except that the binded parameter CURDATE() did not execute properly and the ENTRYDATE cell was assigned 0000-00-00.
Are you sure you are monitoring the same database and table your script is supposedly inserting to?
What happens when going with error_reporting(E_ALL); ?
Have you verified that the script actually completes the insertion?
The following appears to be working as expected:
error_reporting(E_ALL);
try {
$query = "INSERT INTO mytable (NAME, DESCRIPTION, ENTRYDATE) VALUES (?, ?, CURDATE())";
$stmt = $conn->prepare($query);
$name= 'something';
$desc = 'something';
$stmt->bind_param("ss", $name, $desc);
$stmt->execute();
if ($conn->affected_rows < 1) {
throw new Exception('Nothing was inserted!');
}
$stmt->close();
$conn->close();
//redirect to success page
}
catch(Exception $e) {
print $e->getMessage();
}
Are you sure there is no error? There seems to be a typo in your column name for example.
Note that PDO is extremely secretive about errors by default.
See How to squeeze error message out of PDO? on how to fix this.
Try preparing this query instead:
"INSERT INTO mytable (NAME, DESCRIPTION, ENTRYDATE) VALUES(?,?,CUR_DATE())"
And check the results of $stmt->execute(). It would have given you a warning that "CUR_DATE()" (sic) is not a valid DATE.
You can check if a statement was correctly executed by checking the return value of execute() and querying the errorInfo() method:
if (!$stmt->execute()) {
throw new Exception($stmt->errorInfo(), stmt->errorCode());
}
Be aware that upon failure, execute() does not throw an exception automagically. You'll have to check for successful operation and failure for yourself.
Is it possible that autocommit is OFF?
If so then you have to commit your insert like so
/* commit transaction */
$conn->commit();
Regards

Categories