PDO prepared statement with placeholder not work - php

i have some problems with execute a PDO.
No error, just nothing happens. The code looks like:
$stmt = $dbh->prepare("INSERT INTO `member_accounts` ('firstname','lastname','email','password') VALUES (:fname,:lname,:e,:pw)");
$arr = array(
':fname' => $_POST['firstname'],
':lname' => $_POST['lastname'],
':e' => $_POST['email'],
':pw' => $_POST['password'],
);
$stmt->execute($arr);
Anyone see the problem? I'm to new at PDO.. Thanks

Remove single quotes here
('firstname','lastname','email','password')
Right statement will be
$stmt = $dbh->prepare("INSERT INTO `member_accounts` (firstname,lastname,email,password) VALUES (:fname,:lname,:e,:pw)");
You can also use backtick(`) with column name but not single quotes.
$stmt = $dbh->prepare("INSERT INTO `member_accounts` (`firstname`,`lastname`,`email`,`password`) VALUES (:fname,:lname,:e,:pw)");

use the following code
$sql="INSERT INTO `member_accounts`
(firstname,lastname,email,password) VALUES
(:fname,:lname,:e,:pw)";
$stmt = $dbh->prepare($sql);
//pdo $stmt is false if any error occur
if($stmt)
{
$arr = array(
':fname' => $_POST['firstname'],
':lname' => $_POST['lastname'],
':e' => $_POST['email'],
':pw' => $_POST['password'],
);
$stmt->execute($arr);
}

Related

Using array implode for building insert query

I am following tutorials for user registration. This is what I am trying to build query using implode:
if(isset($_POST['submit'])){
$registration_data= array(
'username' => $_POST['username'],
'password' => $_POST['password'],
'password_again' => $_POST['password_again'],
'first_name' => $_POST['first_name'],
'last_name' => $_POST['last_name'],
'email' => $_POST['email']
);
register_user($registration_data);
}
function register_user($registration_data){
global $connect;
$data=implode(',', $registration_data).'}';
$fields= implode(",", array_keys($registration_data));
Now I have to build query like this
$query=INSERT INTO users ($fields) VALUES($data);
// I want data to be formated like this '{$username}', '{$password}',
How can I do it in above mentioned implode functions,
Note: I am just following some basic tutorials so not worried about PDO/ injections etc
You need to put quotes around all the data values before you implode them:
$data = implode(',', array_map(function($x) {
return "'" . $x . "'";
}, $registration_data));
$fields = implode(',', array_keys($registration_data));
$query = "INSERT INTO users ($fields) VALUES ($data)";
Especially if you are just learning on how to do this, you should learn to do them right from the beginning.
You really don't need to use implode() with prepared statements. Just use PDO::prepare() and pass the array to PDOStatement::execute. Pseudo code is along the lines of:
$registration_data= array(
':username' => $_POST['username'],
':password' => $_POST['password'],
':password_agai' => $_POST['password_again'],
':first_name' => $_POST['first_name'],
':last_name' => $_POST['last_name'],
':email' => $_POST['email']
);
$sql='INSERT INTO yourtable VALUES (:username, :password, :password_agai, :first_name, :last_name, :email);';
$qry=$yourpdoconn->prepare($sql);
$qry->execute($registration_data);
Please note that you still need to handle your errors and everything else, but that's the gist of it. mysqli_* can do the same with prepared statements so you aren't necessarily stuck with PDO either.

Inserting placeholders and radio button in SQL table

I have an problem I can't seem to solve.
$query = 'INSERT INTO members (username,password,email,active,owner_service) VALUES ( )';
$stmt = $db->prepare($query);
$stmt->bind_param( );
$stmt->execute(array(
':username' => $_POST['username'],
':password' => $hashedpassword,
':email' => $_POST['email'],
':active' => $activasion,
'"$owner_service"' => $POST_['owner_service']
));
'username, password, email and active' are all placeholders but 'owner_service' is a radio button and I don't know how to write it in code if I want to insert it into my table. Do I use ' :xx ' for the placeholders and ' ? ' for my radio button? So the code will look like
(:username, :password, :email, :active, ?)
and in the bind_param write
('$owner_service') ?

PDO how to treat param variable that can be empty

I have a prepared statement and param with variables, but it's possible that some of these variables may be empty and it gives me an error.. how to treat the code to SKIP the empty param?
CODE:
$stmt = $conn->prepare("insert into account (accountID, firstName, imageURL, sex, cat1) VALUES (:accountID, :firstName, :sourcefilename, :sex, :cat1)");
$stmt->execute(array(
':accountID' => $accountID,
':firstName' => $first_name,
':sourcefilename' => $sourcefilename,
':sex' => $gender,
':cat1' => $cat1));

PDO Invalid parameter number: number of bound variables does not match number of tokens

I have three ":" (names)
$q = $db->prepare('INSERT INTO '.PRFX.'u
(phone,mail,lvl,regdate,act_lnk,joined,name,first_time)
VALUE(:phone,:mail,0,"'.time().'","'.md5(uniqid(mt_rand(),1)).'","'.DATETIME.'",:name,1)');
$q->execute(
array(
'phone'=>$_POST['phone'],
'mail'=>$_POST['mail'],
'name'=>$_POST['name']
)
);
And they're matched. So why I get the error?
Is guess it should be
array(
':phone'=>$_POST['phone'],
':mail'=>$_POST['mail'],
':name'=>$_POST['name']
)
You cannot mix named parameters and real values inside the prepare() method like you do by using 0, time() and other PHP functions.
The prepare() method needs to be free from real values because the DBMS don't expect any and won't parse the query. It only create an execution plan of the query. Your code should look like this:
$q = $db->prepare('INSERT INTO ' . PRFX . 'u
(phone,mail,lvl,regdate,act_lnk,joined,name,first_time)
VALUE(:phone,:mail,:lvl,:regDate,:actLink,:joined,:name,:firstTime)');
$q->execute(
array(
':phone' => $_POST['phone'],
':mail' => $_POST['mail'],
':name' => $_POST['name'],
':lvl' => 0,
':regDate' => time(),
':actLink' => md5(uniqid(mt_rand(),1)),
'joined' => DATETIME,
'firstTime' => 1
)
);
You should also check if the $_POST variables you are going to use are set, not-empty and have the expected type of value.
Furthermore I recommend to use bindValue() for binding the values to the query. Then you can define also the variable type:
$q->bindValue(':phone', $_POST['phone'], PDO::PARAM_STR);
$q->bindValue(':regDate', time(), PDO::PARAM_INT);
...
$q->execute();

phpmyadmin and mysql pdo lastInsertId()

i have this
$query = "INSERT INTO players VALUES (
UUID(),
:firstname,
:lastname,
:age,
:birthplace,
:height,
:weight,
:bats,
:throws,
:position,
:jersey,
:status,
:team,
:image_path
)";
$sth = $db->prepare($query);
$sth->execute(array(
':firstname' => $firstname,
':lastname' => $lastname,
':age' => $age,
':birthplace' => $birthplace,
':height' => $height,
':weight' => $weight,
':bats' => $bats,
':throws' => $throws,
':position' => $position,
':jersey' => $jersey,
':status' => $status,
':team' => $team,
':image_path' => $image_path
));
$id = $db->lastInsertId();
return $id;
and i'm trying to return the last ID that was inserted, and all i'm getting is a 0 returned.
any help is greatly appreciated
thanks
LAST_INSERT_ID() and friends will work only for integer IDs that are created via an AUTO_INCREMENT column. You need to run two queries - first
SELECT UUID() AS newuuid;
then fetch and store this result (e.g. in $uuid), then
"INSERT INTO players VALUES (
:uuid,
:firstname,
:lastname,
...
execute(array(
':uuid' => $uuid,
':firstname' => $firstname,
':lastname' => $lastname,
':age' => $age,
leaving you with the $uuid still valid.

Categories