PHP PDO dynamically getting data - php

Would this code work? If not, what are my options?
$stmt = $db->prepare("SELECT * FROM table WHERE ? = ? AND ? = ?");
$stmt->execute( array( $column1 => $value1, $column2 => $value2 ) );

No, you need to supply the table field names, the values can be substituted.
$stmt = $db->prepare("SELECT * FROM table WHERE column1 = :value1 AND column2= :value2");
$stmt->execute( array( ':value1' => $value1, ':value2' => $value2 ) );
http://www.php.net/manual/en/pdo.prepare.php

Related

How to insert multiple items using foreach loop

I've been trying to insert multiply items using foreach loop in php and mysql. When i insert its insert null values. any ideas as to what i should fix?
$itemNo = $statement->fetchColumn();
$item_name = ($_POST["item_name"]);
$item_price = ($_POST["item_price"]);
$item_quantity = ($_POST["item_quantity"]);
$item_total = ($_POST["item_total"]);
$statement = $connect->prepare("
INSERT INTO product
( `item_no`,`item_name`, `item_price`, `item_quantity`, `item_total`)
VALUES ('$itemNo','$item_name','$item_price','$item_quantity','$item_total')
");
foreach($_POST["item_name"] as $subscription){
$statement->execute(
array(
':itemNo' => $itemNo,
':item_name ' => trim($_POST["item_name"]),
':item_price' => trim($_POST["item_price"]),
':item_quantity' => trim($_POST["item_quantity"]),
':item_total' => trim($_POST["item_total"])
)
);
}
You need to put placeholders in the query, not variables, to match the parameters in the call to execute().
$statement = $connect->prepare("
INSERT INTO product
( `item_no`,`item_name`, `item_price`, `item_quantity`, `item_total`)
VALUES (:itemNo,:item_name,:item_price,:item_quantity,:item_total)
");
And if $_POST['item_name'] is an array, you can't use trim($_POST['item_name']) as a value. The argument to trim() has to be a string, not an array. If these post variables are all arrays, you need to index them.
foreach ($item_name as $index => $subscription) {
$statement->execute(
array(
':itemNo' => $itemNo,
':item_name ' => trim($subscription),
':item_price' => trim($item_price[$index]),
':item_quantity' => trim($item_quantity[$index]),
':item_total' => trim($item_total[$index])
)
);
}

Update Query with PDO becames delete

I have a update query using PDO,
but when I execute it, it deletes my record.
public function update($e) {
$sql = 'UPDATE experiences SET company = :company, position = :position, duty = :duty WHERE id = :id';
//$this->operaction($sql, $e);
$id = $e['id'];
$company = $e['company'];
$position = $e['position'];
$duty = $e['duty'];
$pdostmt = $this->db->prepare($sql);
$pdostmt->bindValue(':id', $id, PDO::PARAM_INT);
$pdostmt->bindValue(':company', $company, PDO::PARAM_STR);
$pdostmt->bindValue(':position', $position, PDO::PARAM_STR);
$pdostmt->bindValue(':duty', $duty, PDO::PARAM_STR);
$pdostmt->execute();
}
$e is an array of $_POST array('id' => '6', 'company' => 'webcanada', 'position' => 'web developer', 'duty' => 'build website');
Can anyone suggest I have done wrong?
Thanks.

Can't access variable for unknown reason

I'm trying to execute two INSERT statements and I need the last inserted id to do so. I've tried $question_id = $dbh->lastInsertId();, but it doesn't work. Now I'm executing an additional SELECT LAST_INSERT_ID() statement, but that doesn't work either. I keep getting this error: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined, which occurs because $question_id is empty because selecting the last insert id doesn't seem to work.
Here's my code:
public function add_question($user_id, $group_id, $title, $caption, $datetime, $status) {
// Add user to database
try {
$dbh = new DBHandler();
$sql =
"INSERT INTO question(
user_id,
group_id,
title,
caption,
created_date_time,
question_status
)
VALUES(
:user_id,
:group_id,
:title,
:caption,
:created_date_time,
:question_status
)";
$stmt = $dbh->get_instance()->prepare($sql);
$stmt->execute(
array(
':user_id' => $user_id,
':group_id' => $group_id,
':title' => $title,
':caption' => $caption,
':created_date_time' => $datetime,
':status' => $status
)
);
//$question_id = $dbh->lastInsertId();
$sql= "SELECT LAST_INSERT_ID() AS question_id";
$stmt = $dbh->get_instance()->prepare($sql);
$stmt->execute();
// Resultset
$result = $stmt->fetchAll();
foreach($result AS $question_id_row) {
$question_id = $question_id_row['question_id'];
}
$sql =
"INSERT INTO notification(
n_question_id,
n_question_user_id,
n_question_group_id,
n_question_title
)
VALUES(
:n_question_id,
:n_question_user_id,
:n_question_group_id,
:n_question_title
)";
$stmt = $dbh->get_instance()->prepare($sql);
$stmt->execute(
array(
':n_question_id' => $question_id,
':n_question_user_id' => $user_id,
':n_question_group_id' => $group_id,
':n_question_title' => $title
)
);
echo 'Question added!';
}
catch(PDOException $e) {
echo $e->getMessage();
}
}
Your query fails with invalid number of parameter and parameter was not defined because you define this parameter
:question_status
but you bind
':status' => $status
change
$stmt->execute(
array(
':user_id' => $user_id,
':group_id' => $group_id,
':title' => $title,
':caption' => $caption,
':created_date_time' => $datetime,
':question_status' => $status //here
)
);
and it will work

Dynamic prepared statement (bind param error)

I'm trying to be able to add parameters to to my prepared statement, query and arrays look right. But the "Number of elements in type definition string doesn't match number of bind variables" error is triggered.
$sql = 'SELECT * FROM `feed` ';
$types = array();
$params = array();
if( isset($_GET['p']) ) {
$page = $_GET['p'];
}
else {
$page = 0;
}
if( isset($_GET['q']) ) {
$sql .= 'WHERE `title` LIKE ? ';
$search = $_GET['q'];
array_push($types, 's');
array_push($params, $search);
}
$sql .= 'ORDER BY `time` DESC LIMIT ?, 6';
array_push($types, 'i');
array_push($params, $page);
$stmt = $mysqli->prepare($sql);
$params = array_merge($types, $params);
$refs = array();
foreach($params as $key => $value)
$refs[$key] = &$params[$key];
call_user_func_array(array($stmt, 'bind_param'), $refs);
(Printed from the server)
Query: SELECT * FROM feed WHERE title LIKE ? ORDER BY time DESC LIMIT ?, 6
Array merge:
Array
(
[0] => s
[1] => i
[2] => word
[3] => 0
)
Thanks.
My understanding is that the first parameter 'types' is a string of the types of the parameters, not an array. so the the parameter list for the example should look like:
Array
(
[0] => si
[1] => word
[2] => 0
)
This is untested code: but implode should do what we want from the '$types' array
$strTypes = implode('', $types);
i will check it later.

About creating an array at php

I am having trouble at creating a specific array.
What i want is to pull the info for my members (from mysql database) and then store them to an array.
The array should be like this:
$members = array(
'John' => array('avatar' => '/images/avatar/ji.jpg', 'country' => 'uk.'),
'Nick' => array('avatar' => '/images/avatar/nick.jpg', 'country' => 'italy.'),
);
etc..
so i pull the name,avatar url and country from the db and then i store them in to the previous array.
My question is, how could i create this array?
Thanks in advance!
About creating an array at php.
Something like this should work:
$members = array();
$q = mysql_query("SELECT name , avatar, country from table");
while($row = mysql_fetch_assoc($q)){
$array = array("avatar" => $row['avatar'] , "country" => $row['country']);
$members[$row['name']] = $array;
}
Using PDO:
$members = array();
$conn = new PDO("mysql:host=$host;dbname=$database", $username, $password);
$sql = "SELECT name, avatar, country FROM members";
foreach ($conn->query($sql) as $row) {
$temp = array('avatar' => $row['avatar'], 'country' => $row['country']);
$members[$row['name']] = $temp;
}

Categories