Update Query with PDO becames delete - php

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.

Related

Can't get MySQL Update query to work with jsgrid

I currently have this code connected to a JSGrid table:
$connect = new PDO("mysql:host=localhost;dbname=localDatabase", "root", "root");
$method = $_SERVER['REQUEST_METHOD'];
$query = "SELECT COUNT(*) FROM stmr";
$link = mysqli_connect("localhost","root", "root", "localDatabase");
$result = mysqli_query($link, $query);
$form_id = mysqli_fetch_array($result)[0] + 1;
if($method == 'GET')
{
$data = array(
':item_id' => "%" . $_GET['item_id'] . "%",
':description' => "%" . $_GET['description'] . "%",
':part_number' => "%" . $_GET['part_number'] . "%",
':unit' => "%" . $_GET['unit'] . "%",
':quantity' => "%" . $_GET['quantity'] . "%"
);
$query = "SELECT * FROM stmrdesc WHERE item_id LIKE :item_id AND description LIKE :description AND part_number LIKE :part_number AND unit LIKE :unit AND quantity LIKE :quantity ORDER BY item_id DESC";
$statement = $connect->prepare($query);
$statement->execute($data);
$result = $statement->fetchAll();
foreach($result as $row)
{
$output[] = array(
'id' => $row['row_id'],
'item_id' => $row['item_id'],
'description' => $row['description'],
'part_number' => $row['part_number'],
'unit' => $row['unit'],
'quantity' => $row['quantity']
);
}
header("Content-Type: application/json");
echo json_encode($output);
}
if($method == "POST")
{
$data = array(
':item_id' => $_POST['item_id'],
':description' => $_POST['description'],
':part_number' => $_POST["part_number"],
':unit' => $_POST["unit"],
':quantity' => $_POST["quantity"]
);
$query = "INSERT INTO stmrdesc (item_id, description, part_number, unit, quantity) VALUES (:item_id, :description, :part_number, :unit, :quantity)";
$statement = $connect->prepare($query);
$statement->execute($data);
}
if($method == 'PUT')
{
parse_str(file_get_contents("php://input"), $_PUT);
$data = array(
':item_id' => $_PUT['item_id'],
':description' => $_PUT['description'],
':part_number' => $_PUT['part_number'],
':unit' => $_PUT['unit'],
':quantity' => $_PUT['quantity']
);
$query = "
UPDATE 'stmrdesc'
SET 'item_id' = ':item_id',
'description' = ':description',
'part_number' = ':part_number',
'unit' = ':unit',
'quantity' = ':quantity'
WHERE 'id' = ':id'
";
$statement = $connect->prepare($query);
$statement->execute($data);
}
if($method == "DELETE")
{
parse_str(file_get_contents("php://input"), $_DELETE);
$query = "DELETE FROM stmrdesc WHERE id = '".$_DELETE["id"]."'";
$statement = $connect->prepare($query);
$statement->execute();
}
As you can see, I have a method that is connected to each of the buttons of the JSGrid table and all work (submit the changes to the database) except the PUT Method that edits and updates the row in the database.
The put sql statement has WHERE 'id' = ':id' but ':id' does not exist in the $data array.

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

PHP PDO dynamically getting data

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

PDO, check for empty string and don't update if empty

If I run my function edit_profile() without any parameter, then empty strings are written in DB. If $input['email'] is empty for example, I'd like UPDATE not to update this column.
I tried to do:
SET email = IF(LENGTH(:email)=0, email, :email),
It didn't work, I'm not sure how to do same as above with PDO.
function edit_profile($input) {
//
$user_id = 1;
//
try {
//
$conn = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME, DB_USERNAME, DB_PASSWORD);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('UPDATE users SET
email = :email,
password = :password,
name_surname = :name_surname,
age = :age,
sex = :sex,
education = :education,
avatar = :avatar
WHERE id = :id');
$stmt->execute(array(
':id' => $user_id,
':email' => $input['email'],
':password' => $input['password'],
':name_surname' => $input['name_surname'],
':age' => $input['age'],
':sex' => $input['sex'],
':education' => $input['education'],
':avatar' => $input['avatar']
));
echo $stmt->rowCount(); // 1
//
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
//
}
edit_profile();
Try
UPDATE users SET
email = COALESCE(NULLIF(:email, ''),email),
password = :password,
name_surname = :name_surname,
age = :age,
sex = :sex,
education = :education,
avatar = :avatar
WHERE id = :id
I'm basically trying to use COALESCE (http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_coalesce) to use :email only if not null. If it's null, use the old email.
In case :email is empty string and not simply NULL, I've added NULLIF to convert the empty string to NULL ;)
SET email = IF(LENGTH(:email1)=0, email, :email2)
$stmt->execute(array(
':id' => $user_id,
':email1' => $input['email'],
':email2' => $input['email'],
':password' => $input['password'],
':name_surname' => $input['name_surname'],
':age' => $input['age'],
':sex' => $input['sex'],
':education' => $input['education'],
':avatar' => $input['avatar']
));

UPDATE an array using PDO

I'm creating a multi-step form for my users. They will be allowed to update any or all the fields. So, I need to send the values, check if they are set and if so, run an UPDATE. Here is what I have so far:
public function updateUser($firstName, $lastName, $streetAddress, $city, $state, $zip, $emailAddress, $industry, $password, $public = 1,
$phone1, $phone2, $website,){
$updates = array(
'firstName' => $firstName,
'lastName' => $lastName,
'streetAddress' => $streetAddress,
'city' => $city,
'state' => $state,
'zip' => $zip,
'emailAddress' => $emailAddress,
'industry' => $industry,
'password' => $password,
'public' => $public,
'phone1' => $phone1,
'phone2' => $phone2,
'website' => $website,
);
Here is my PDO (well, the beginning attempt)
$sth = $this->dbh->prepare("UPDATE user SET firstName = "); //<---Stuck here
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
return $result;
Basically, how can I create the UPDATE statement so it only updates the items in the array that are not NULL?
I thought about running a foreach loop like this:
foreach($updates as $key => $value) {
if($value == NULL) {
unset($updates[$key]);
}
}
but how would I write the prepare statement if I'm unsure of the values?
If I'm going about this completely wrong, please point me in the right direction. Thanks.
First of all, use array_filter to remove all NULL values:
$updates = array_filter($updates, function ($value) {
return null !== $value;
});
Secondly, bind parameters, that makes your live a lot easier:
$query = 'UPDATE table SET';
$values = array();
foreach ($updates as $name => $value) {
$query .= ' '.$name.' = :'.$name.','; // the :$name part is the placeholder, e.g. :zip
$values[':'.$name] = $value; // save the placeholder
}
$query = substr($query, 0, -1).';'; // remove last , and add a ;
$sth = $this->dbh->prepare($query);
$sth->execute($values); // bind placeholder array to the query and execute everything
// ... do something nice :)
The below can be optimized:
$i = 0; $query = array();
foreach($updates as $key => $value) {
if ($value != NULL) {
$query[] = "{$key} = :param_{$i}";
$i++;
}
}
if (! empty($query)) {
$finalQuery = implode(",", $query);
$sth = $this->dbh->prepare('UPDATE user SET ' . $finalQuery);
$i = 0;
foreach($updates as $key => $value) {
if ($value != NULL) {
$sth->bindParam(':param_'.$i, $value, PDO::PARAM_STR);
$i++;
}
}
}

Categories