Inserting data into MySQL database using PDO - php

I'm new to PHP and MySQL and I'm trying to insert data in to a database, which had worked fine until i attempted to use PDO's prepare method. It returns the catch error and i cannot figure out why - i'd also like to know whether it's best practice to use unnnamed placeholders or named placeholders?
The username and password variables are defined earlier in my code and catches data from the user using $_POST.
EDIT: getMessage() error displays SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'username' cannot be null
if (!empty($user) && (!empty($password)) ) {
try {
$results = $db->prepare("INSERT INTO user_info (username, pass) VALUES (?,?)");
$results->bindParam(1,$username);
$results->bindParam(2,$password);
$results->execute();
} catch (Exception $e) {
echo "Could not insert data in to the database";
}
}

You have two different variable names. You're checking $user to make sure it's not empty() but then you tell bind $username to the first parameter. You'll just need to rename one of them to match the other.

Try this one.
if (!empty($user) && (!empty($password)) ) {
try {
$results = $db->prepare("INSERT INTO user_info (username, pass) VALUES (?,?)");
$results->bindParam(1,$user);
$results->bindParam(2,$password);
$results->execute();
} catch (Exception $e) {
echo "Could not insert data in to the database";
}
}
Please try yourself first to find the error.

Related

Why do I get an error when trying to execute this SQL statement on PHP Storm [duplicate]

This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed last year.
I have an insert statement that is executed with PDO. Insert works great however if there is an error I would like it displayed to the user.
I have the below try-catch block.
try{
$insertuser = $db->prepare('INSERT INTO `she_she`.`Persons` (`idnumber`,`addedby`,`firstname`, `middlename`, `surname`, `fullname`, `gender`, `birthdate`, `homelanguage`, `department`, `employeetype`, `employeestatus`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)');
$insertuser->execute(array($idnumber,$user,$firstname, $middlename, $surname, $fullname, $gender, $birthdate, $language, $department, $employmenttype, $personstatus));
}
catch(PDOException $exception){
return $exception;
}
If the query fails, or let's say a duplicate IDNumber, I want this displayed to the user.
If I simply try to echo the variable $exception it does not work.
I want to return the MySQL error to the user.
By default PDO is not in a state that will display errors. you need to provide the following in your DB connection
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
More info can be seen Here
1.Add ERRMODE_EXCEPTION mode after your db connection:
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
2.And than you must use try{} catch{} method for all your mysql query. Like this:
try {
$SQL = "DELETE FROM items WHERE item_id=:item_id";
$m = $dbh->prepare($SQL);
$m->bindParam(':item_id', $item_id, PDO::PARAM_INT);
$m->execute();
//success
$return = "Your success message.";
}
catch (PDOException $e) {
//error
$return = "Your fail message: " . $e->getMessage();
}
You should use this:
return $exception->getMessage();
See the page on the documentation of Exception class:
http://www.php.net/manual/en/exception.getmessage.php

How to insert unique email into mysql table [duplicate]

This question already has answers here:
How to prevent duplicate usernames when people register?
(4 answers)
Closed 12 months ago.
I want to take email addresses from users to add them to a mailing list. However, I want to prevent duplicate entries, so I am using the INSERT IGNORE approach. I am using the PHP script below, but constantly receive this error:
Fatal error: Uncaught Error: Call to a member function bind_param() on bool
I've reviewed a LOT of SO articles on this error but still can't get it to work. I have confirmed that the $email and $id variables do have values. I suspect the error must have something to do with the use of IGNORE, but I honestly don't know.
Here's my code:
$email = filter_input(INPUT_POST, 'email',FILTER_SANITIZE_EMAIL);
$id = filter_input(INPUT_POST, 'id',FILTER_VALIDATE_INT) ?: NULL;
$sqlQuery = 'INSERT IGRNORE INTO email(email, id) VALUES(:email,:id);';
$stmt = $dbc->prepare($sqlQuery);
$stmt->bind_param(':email',$email);
$stmt->bind_param(':id',$id);
$stmt->execute();
mysqli_close($dbc);
I've tried including only one variable for the insert but I get the error against both bind_param lines. I also got the error when I had this structured to have both variables in a single bind_param entry.
I'm open to other ways of avoiding duplicate emails in the database, so long as they can be done with a single PHP file.
You are mixing PDO and mysqli syntax. You need to pick one.
PDO
Open the connection, execute the statement without IGNORE, and then catch the exception to see why it failed. The code 1062 means that MySQL tried to insert a duplicate value.
$pdo = new PDO("mysql:host=localhost;dbname=test;charset=utf8mb4", 'user', 'pass', [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_EMULATE_PREPARES => false
]);
try {
$stmt = $pdo->prepare('INSERT INTO email(email, id) VALUES(:email,:id)');
$stmt->execute([
'email' => $email,
'id' => $id
]);
} catch (PDOException $e) {
if ($e->errorInfo[1] === 1062) {
// duplicate
} else {
// If not 1062 then rethrow
throw $e;
}
}
mysqli
Using mysqli it's a little bit more work, but the same logic. With mysqli you can't use named placeholders and you can't bind-in-execute. The bind_param() function is very peculiar so pay special attention to the syntax.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'user', 'pass', 'test');
$mysqli->set_charset('utf8mb4'); // always set the charset
try {
$stmt = $mysqli->prepare('INSERT INTO email(email, id) VALUES(?, ?)');
$stmt->bind_param('ss', $email, $id);
$stmt->execute();
} catch (mysqli_sql_exception $e) {
if ($e->getCode() === 1062) {
// duplicate
} else {
// If not 1062 then rethrow
throw $e;
}
}

Attempting to insert new row into database using PDO

Ok, so I've been trying to do this for days, and I've been reading all sorts of tutorials, but I seem to be missing something, because I still can't get it. I'm working on learning about web forms and inserting the form input into the respective database. I'm able to take the info from the form and echo it on the result page, so I know that all works. but I can't seem to get the form input to go into my database. I know the connection works, so there must be something wrong with my syntax.
PHP
//DB Configs
$username = null;
$password = null;
try {
$db = new PDO("mysql:host=localhost;dbname=Testing3", $username, $password);
//Set the PDO error mode to exception (what does this mean?)
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Prepare SQL and bind parameters
$sql = $db->prepare("INSERT INTO `NFK_SPECIES` (`Name`)
VALUES (:name)");
//Insert a Row
$species = $_POST['Species'];
$sql->execute(array(':name'=>$species));
}
catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
$result = $db->query('SELECT * from `NFK_Species` ORDER BY `Id` DESC');
//Query
/*
$input = $db->query("INSERT INTO `NFK_Species` (`Id`, `Name`) VALUES (Null, `$species`)");
$result = $db->query('SELECT * from `NFK_Species` ORDER BY `Id` DESC');*/
//Kill Connection
$db = Null;
}
HTML/PHP (web page)
<h1>Inserting a New Species into Database:</h1>
<h3>Results</h3>
<?php
if ($sql->execute()){
echo "Data input was successful";
while ($rows = $result->fetch()){
echo $rows['Name']; echo ", ";
}
} else {
echo "Data input failed."; echo mysql_error();
}
?>
This is only my current attempt at doing this. I prefer the attempt I had before, with the bindParam and simple execute(), so if I could get that to work instead, I'd appreciate it. The following example also has the Id column for this table. This is an auto-increment column, which I read doesn't need to be included, so I excluded it from my recent attempt. Is that correct?
Past PHP
//Prepare SQL and bind parameters
$sql = $db->prepare("INSERT INTO `NFK_SPECIES` (`Id`, `Name`)
VALUES (Null, :name)");
$sql->bindParam(':name', $species);
//Insert a Row
$species = $_POST['Species'];
$sql->execute();
I've been reading a bunch of tutorials (or trying to), including attempting to decipher the php.net tutorials, but they all seem to be written for people who already have a good handle on this and experience with what's going on, and I'm very new to all of this.
Alright, I was able to figure out my problem, and then successfully insert a row using my code.
Debugging:
So the code posted above was breaking my code, meaning my page wouldn't load. I figured that meant that there was a syntax error somewhere, but I couldn't find it, and no one else had located it yet. Also, that meant that my Error Alerts weren't working to let me know what the problem was. If you look at my original PHP sample, you'll see down at the very bottom there is a single "}" just hanging out and serving no purpose, but more importantly, it's breaking the code (stupid, hyper-sensitive php code). So I got rid of that, and then my Error messages started working. It said I couldn't connect to my database. So I look over my database login syntax, which looked fine, and then you'll notice in my 1st php sample that somehow I'd managed to set my $username and $password to NULL. Clearly that isn't correct. So I fixed that, and next time I refreshed my page, I'd successfully entered a row in my database! (yay)
Note:
In my original php sample, I'd included the Id Column, which is auto-incremented, for the row insertion, with a value of NULL. This worked, and it inserted the row. Then I experimented with leaving it out altogether, and it still worked. So the updated working code below doesn't include the Species Id.
Working code:
<body>
<h1>Inserting a New Species into Database:</h1>
<h3>Results</h3>
<?php
//DB Configs
$username = root;
$password = root;
try {
//Connect to Database
$db = new PDO("mysql:host=localhost;dbname=Testing3", $username, $password);
//Enable PDO Error Alerts
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Prepare SQL statement and bind parameters
$sql = $db->prepare("INSERT INTO `NFK_SPECIES` (`Name`) VALUES (:name)");
$sql->bindParam(':name', $species);
//Insert a Row
$species = $_POST['Species'];
$sql->execute();
// Echo Successful attempt
echo "<p class='works'><b>" . $species . "</b> successfully added to database.</p></br></br>";
}
catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
// Gather updated table data
$result = $db->query('SELECT * from `NFK_Species` ORDER BY `Id` DESC');
//Kill Connection
$db = Null;
while ($rows=$result->fetch()){
echo $rows['Id']; echo " - "; echo $rows['Name']; echo "</br>";
}
?>
<body>

Insertig php array in mysql DB - Syntax correct, values are not inserted

I have writen this pice of code that should insert into my Database some event data, but it does not insert a thing in the DB, can you tell me why?
try {
$pdo = new PDO("mysql:host={$dbhost};dbname={$dbname}", $dbuser, $dbpass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch( PDOException $excepiton ) {
echo "Connection error :" . $excepiton->getMessage();
}
try{
$sql = "INSERT INTO events_DB (event_id, event_end_time, event_location, event_name) VALUES (:event_id, :event_end_time, :event_location, :event_name) ON DUPLICATE KEY UPDATE event_id = :event_id, event_end_time = :event_end_time, event_location = :event_location, event_name = :event_name";
$stm = $db->prepare($sql);
$stm->execute(array(":event_id" => $event[id], ":event_end_time" => $event[end_time], ":event_location" => $event[location], ":event_name" => $event[name]));
}
catch ( PDOException $exception )
{
// decomentati sa vedeti erorile
echo "PDO error :" . $exception->getMessage();
}
Thanks
The code you've posted is different than the code you're running as the posted code would result in a syntax error at parse time and never actually run.
However, what's happening is the SQL being sent to the prepare method is not valid in some way so that the result returned and stored in $stm is a boolean (false) rather than a valid statement object. Double check your SQL (you could try running it in another application such as phpMyAdmin or via the mysql command-line program) to ensure its validity. You could also add some error handling to find the cause with:
$stm = $db->prepare($sql);
if (!$stm) {
die($db->errorInfo());
}
Edit: You've modified the posted source code which now shows use of exception handling. However, you've commented out the line that echos the exception message. This information will be useful in telling you what's causing the error condition. Uncomment to see the message (which will most likely inform you that the SQL is invalid and which part of it caused the error).
Try to remove the <br> tag from the first line and a " is messing
$sql = "INSERT INTO events_DB (event_id, event_end_time, event_location, event_name);"

PDO - catching when the database contraints prevent query from executing fully

I have a register.php file which takes the input from a form and tries to create a user account in a database. I have an innoDB MySQL database which has a 'UNIQUE' key added to the 'username' field of the users table. This is to prevent duplicate usernames.
Below is an extract from my php code. In my database I currently have a user called 'testUser'. However, when running the code below with $username = testUser, the php file returns 'Account created', even though a duplicate row is not created in the database. I would have expected there to be an exception thrown if the user already existed?
try{
$stmt = $db->prepare("INSERT INTO users (username, password, salt) VALUES (:username, :password, :salt)");
$stmt->bindParam(':username', $username);
$stmt->bindParam(':password', $hash);
$stmt->bindParam(':salt', $salt);
$stmt->execute();
}catch(PDOException $e){
returnJSON(0,'Error creating account');
}
returnJSON(1,'Account created');
function returnJSON($errorCode, $message){
$arr = array("returnCode" => $errorCode, "returnMessage" => $message);
echo json_encode($arr);
die();
}
----
try{
$db = new PDO('mysql:host='.$host.';dbname='.$dbname, $username, $password);
}
catch(PDOException $e){
$arr = array("returnCode" => 0, "returnMessage" => "unable to connect to server");
echo json_encode($arr);
die();
}
My question is, how should I find out if the user's account was successfully added to the database.
PS. I do have code to query the database first and see if there exists a user with the same name before calling this code. But I'd still like to fix/understand this as well.
PDO by default has silent errors: you need to check then yourself by actually looking for them.
If you want to use exceptions, you need to tell PDO to do it. Check http://php.net/manual/en/pdo.error-handling.php
The specific code you want is
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
in the try/catch immediately after you create the connection.
catch (PDOException $er) {print("error".$er."<br />");}
When you catch an Error, the flow of the program continues, try catching the Error and stopping the flow, using exit();
What I am saying is , even if an exception is caught, the following line of code should stil execute,
returnJSON(1,'Account created');
unless you are stopping the flow somehow. Would really appreciate if you post the entire file, including functions you are using.

Categories