Data not getting stored in database but no error - php

Hello I wrote the following code
PHP
<?php
try{$bdd = new PDO('mysql:host=localhost;dbname=test', 'root', '');}
catch (Exception $e){die('Error: ' . $e->getMessage());}
$req = $bdd->prepare('insert into signup
(email, password, service, phone)
values(:email, :password, :service, :phone_number) ');
$req->execute(array(
'email' => htmlspecialchars($_POST['email']),
'password' => htmlspecialchars($_POST['password']),
'service' => htmlspecialchars($_POST['service']),
'phone_number' => htmlspecialchars($_POST['phone_number'])));
echo 'Well done';
print_r($_POST);
?>
I have a "Well done" message and
Array ( [email] => test#test.test [password] => test[confirm_password] => test[service] => pizza [phone_number] => 01234 )
when I execute my code. But nothing in my DB.
Where is my mistake?

You are only catching an exception if connection fails, not when actually inserting using execute. Either use two # try/catch, or expand the scope of your try & move your catch.
<?php
try
{
$bdd = new PDO('mysql:host=localhost;dbname=test', 'root', '');
$req = $bdd->prepare('insert into signup
(email, password, service, phone)
values(:email, :password, :service, :phone_number) ');
$req->execute(array(
'email' => htmlspecialchars($_POST['email']),
'password' => htmlspecialchars($_POST['password']),
'service' => htmlspecialchars($_POST['service']),
'phone_number' => htmlspecialchars($_POST['phone_number'])));
echo 'Well done';
print_r($_POST);
}
catch (Exception $e)
{
die('Error: ' . $e->getMessage());
}
?>

Related

Why can't I use execute() for an array?

I'm trying to implement a verification email process to my website but I got an error
Fatal error: Uncaught Error: Call to a member function execute() on
bool in :56 Stack trace: #0 {main} thrown in on line 56
Here is my code:
$user_activation_code = md5(rand());
// Nuevo Usuario
$hashed = password_hash($password,PASSWORD_DEFAULT);
$insert_query = 'INSERT INTO clientes (full_name,email,user_activation_code,user_email_status,password,permissions,street,numero,interior,city,state,zip_code,country) VALUES ("$name","$email","$user_activation_code",:user_email_status,"$hashed",cliente,"$street","$numero","$interior","$city","$state","$zip_code",Mexico)';
$statement = $db->prepare($insert_query);
$statement -> execute(
array(
'full_name' => $_POST['name'],
'email' => $_POST['email'],
'password' => $hashed,
'user_activation_code' => $user_activation_code,
':user_email_status' => 'no verificado'
)
);
$result = $statement->fetchAll();
You need to properly bind your array to the query.
PDO for using an associative array you need to have the values in both the query string and the same values in your key.
$insert_query = 'INSERT INTO clientes (full_name,email,user_activation_code,user_email_status,password,permissions,street,numero,interior,city,state,zip_code,country) VALUES (:full_name,:email,:user_activation_code,:user_email_status,:password,"cliente","$street","$numero","$interior","$city","$state","$zip_code","Mexico")';
array(
':full_name' => $_POST['name'],
':email' => $_POST['email'],
':password' => $hashed,
':user_activation_code' => $user_activation_code,
':user_email_status' => 'no verificado'
)
Please also bind your other values such as: $city, $state etc.

Inserting datetime NOW() in database with prepared statements

I'm trying to insert date when user make registration but doesn't work. It didn't insert anything when I add NOW() to the query. If I remove it user is added into database.
This is normal query
$stmt = $pdo->prepare('INSERT INTO users (username,password,email,active) VALUES (:username, :password, :email, :active');
$stmt->execute(array(
':username' => $_POST['username'],
':password' => $hashedpassword,
':email' => $_POST['email'],
':active' => $activasion
));
I've read other threads and tried this
$stmt = $pdo->prepare('INSERT INTO users (username,password,email,created,active) VALUES (:username, :password, :email, NOW(), :active');
$stmt->execute(array(
':username' => $_POST['username'],
':password' => $hashedpassword,
':email' => $_POST['email'],
':active' => $activasion
));
just added created and NOW() to the query but didn't insert anything.
What can be the problem?
You are missing closing parenthesis on the SQL you are feeding to prepare():
$stmt = $pdo->prepare('INSERT INTO users (username,password,email,created,active) VALUES (:username, :password, :email, NOW(), :active');
It should be
$stmt = $pdo->prepare('INSERT INTO users (username,password,email,created,active) VALUES (:username, :password, :email, NOW(), :active)');
As #VincentDecaux suggests, your error checking should catch this. Use the following to enable exceptions, if that's what you prefer:
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Try ths
$created = date("Y:m:d h:i:s");
$stmt = $pdo->prepare('INSERT INTO users (username,password,email,created,active) VALUES (:username, :password, :email, :created, :active');
$stmt->execute(array(
':username' => $_POST['username'],
':password' => $hashedpassword,
':email' => $_POST['email'],
':active' => $activasion,
':created' => $created
));
First try to catch your error :
try {
$stmt = $pdo->prepare('INSERT INTO users (username,password,email,created,active) VALUES (:username, :password, :email, NOW(), :active');
$stmt->execute(array(
':username' => $_POST['username'],
':password' => $hashedpassword,
':email' => $_POST['email'],
':active' => $activasion
));
}
catch(Exception $e) {
echo 'Exception -> ';
var_dump($e->getMessage());
}
Then, you can use this way :
$stmt->execute(array(
':username' => $_POST['username'],
':password' => $hashedpassword,
':created' => date('Y-m-d H:i:s'),
':email' => $_POST['email'],
':active' => $activasion
));

Query looks OK but I have error

I have this SQL Query
$sql = $conn->prepare('INSERT INTO Accounts (Status, Username, Password, FirstName, LastName, EmailAddress, API_Status, API_Key, About) VALUES (:Status, :Username, :Password, :FirstName, :LastName, :EmailAddress, :API_Status, API_Key, :About)');
$sql->execute(array('Status' => 'NotActive', 'Username' => $Username, 'Password' => $PasswordHash, 'FirstName' => $FirstName, 'LastName' => $LastName, 'EmailAddress' => $EmailAddress, 'API_Status' => 'OFF', 'API_Key' => $API_Key, 'About' => $Other));
When executing this query I'm using try { and
catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
Now when I run script Iget this PHP error:
Catchable fatal error: Object of class PDOStatement could not be
converted to string in /var/www/html/register.php on line 94
How I can slove this problem?
Problems with question.
Wrong naming. SQL is a text that is passed to prepare(). While returned value is an object. Problem not solved.
Due to wrong naming the OP is trying to echo an object. Problem not solved.
Thanks to the great site of Stack Overflow, the OP is taught terrible wrong way of handling PDO errors, with useless try..catch stuff. Problem not solved.
: is missed for one placeholder. The only problem solved.
As a result, next time this query throws an exception, THE SAME UTTERLY USELESS and irrelevant error message will be produced.
What should be done instead?
$sql = 'INSERT INTO Accounts
(Status, Username, Password, FirstName, LastName, EmailAddress,
API_Status, API_Key, About)
VALUES (:Status, :Username, :Password, :FirstName,
:LastName, :EmailAddress, :API_Status, :API_Key, :About)';
$data = array(
'Status' => 'NotActive',
'Username' => $Username,
'Password' => $PasswordHash,
'FirstName' => $FirstName,
'LastName' => $LastName,
'EmailAddress' => $EmailAddress,
'API_Status' => 'OFF',
'API_Key' => $API_Key,
'About' => $Other
);
$conn->prepare($sql)->execute($data);
What do we have here?
proper naming. if one have a fancy of echoing an SQL query, they will be no mistaken.
readability. No long and windy code off the screen, allowing us to visually inspect the query and find the syntax error.
corrected placeholder syntax.
no statement object is echoed. Neither SQL is, as it makes very little sense in case of a prepared statement.
no stupid try..catch block. Means PHP will be able to notify PHP user in case of error occurred.
you can't echo your sql as you are using, you may need to use debugDumpParams() try something like this.
$sql = $conn->prepare('INSERT INTO Accounts (Status, Username, Password, FirstName, LastName, EmailAddress, API_Status, API_Key, About) VALUES (:Status, :Username, :Password, :FirstName, :LastName, :EmailAddress, :API_Status, API_Key, :About)');
$sql->execute(array(':Status' => 'NotActive', ':Username' => $Username, ':Password' => $PasswordHash, ':FirstName' => $FirstName, ':LastName' => $LastName, ':EmailAddress' => $EmailAddress, ':API_Status' => 'OFF', ':API_Key' => $API_Key, ':About' => $Other));
echo $sql->debugDumpParams();

PDO Insert SQL not executing with no errors

I am running this code:
$stmt = $pdo_conn->prepare("INSERT into ticket_updates (ticketnumber, notes, datetime, contact_name, contact_email, customer, internal_message, type) values (:ticketnumber, :notes, :datetime, :contact_name, :contact_email, :customer, :internal_message, :type) ");
$stmt->execute(array(':ticketnumber' => $ticketnumber,
':notes' => $TicketSummary,
':datetime' => date("Y-m-d H:i:s"),
':contact_name' => $Ticket_ContactName,
':contact_email' => $Ticket_ContactEmail,
':customer' => 'Y',
':internal_message' => 'N',
':type' => 'update'));
all the table columns exist and are correct but its not getting past this point
i tried a var_dump($stmt); but get nothing
Use the following to verify the connection is established correctly
try
{
$dbh = new PDO("mysql:host=xxxxxxxxxxxx;dbname=streaming", "xxxx", "xxxx");
}
catch (Exception $e)
{
throw new Exception( 'Something really gone wrong', 0, $e);
}
You can also output errors when you execute like so
$sth->execute() or die(print_r($sth->errorInfo(), true));
Finally you may also need to enable errors on the page, so place this in the header of your page or at the very top if it is a single page:
error_reporting(-1);
The minus 1 means that it will print all errors.
Until you have discovered the error it is very hard to diagnose the issue further, but the issue likely falls down to either the connection to the database or how you have formed the parameter array.
Add error reporting to your pdo:
$pdo_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
before executing the insert command.
Then on the insert command, output your errors
$stmt->execute(array(':ticketnumber' => $ticketnumber,
':notes' => $TicketSummary,
':datetime' => date("Y-m-d H:i:s"),
':contact_name' => $Ticket_ContactName,
':contact_email' => $Ticket_ContactEmail,
':customer' => 'Y',
':internal_message' => 'N',
':type' => 'update')) or die("ERROR: " . implode(":", $pdo_conn->errorInfo()))
This should give you an indication of what is wrong and why things are not executing as expected.

Internal Server Error Zend Query

Is something wrong with my query
The server encountered an internal error or misconfiguration and was unable to complete your request.
Please contact the server administrator, ##ServerAdmin## and inform them of the time the error occurred, and anything you might have done that may have caused the error.
More information about this error may be available in the server error log.
$sql = $db->query(
"INSERT INTO users (user_id, title, first_name, last_name, user_identity_id, email_id, password, office_phone_number, public_id, session_id, address_id, created_by, last_modified_by, created_on, last_modified_on, is_activated, is_deprecated, middle_name, cell_phone_number, superviser_name, superviser_email, superviser_phone_number)
VALUES( :p_user_id,:p_title,:p_first_name,:p_last_name,:p_user_identity_id,:p_email_id,:p_password,:p_office_phone_number,:p_public_id,:p_session_id,:p_address_id,:p_created_by,:p_last_modified_by,:p_created_on,:p_last_modified_on,:p_is_activated,:p_is_deprecated,:p_middle_name,:p_cell_phone_number,:p_superviser_name,:p_superviser_email,:p_superviser_phone_number)",
array(
'p_user_id' => '',
'p_title' => $title,
'p_first_name' => $first_name,
'p_last_name' => $last_name,
'p_user_identity_id' => '',
'p_email_id' => $email,
'p_password' => $pass,
'p_office_phone_number' => $office_ph_no,
'p_public_id' => '',
'p_session_id' => '',
'p_address_id' => '',
'p_created_by' => '',
'p_last_modified_by' => '',
'p_created_on' => '',
'p_last_modified_on' => '',
'p_is_activated' => '',
'p_is_deprecated' => '',
'p_middle_name' => $middle_name,
'p_cell_phone_number' => $cell_ph_no,
'p_superviser_name' => $supervisor_name,
'p_superviser_email' => $supervisor_email,
'p_superviser_phone_number' => $supervisor_ph_no
)
);
$db->commit();
This looks like you're trying to execute a PDO statement using named parameters in Zend.
First thing to check, I assume you've started a transaction?
Also, in my experience named parameters are the same in the query as in the params array, e.g. :param1 is $params = array(':param1'=>'data');
I use the same method as described in the ZF docs "executing a statement using named parameters":
$select = 'select col1,col2 from my_table where con1=:param1 and con2=:param2';
$params = array(
':param1'=> 'somedata',
':param2'=> 'someotherdata'
);
$statement = new Zend_Db_Statement_Pdo($db,$sql);
if($statement->execute($params)){
//ok!
}

Categories