Jump to content

How would you check if a variable was submitted into a field then submit it to the PDO statement?


Q695
Go to solution Solved by NotionCommotion,

Recommended Posts

Going from something like:

$sql_update='';
$binders='';
if(isset($_POST['name']) && $_POST['name']!=''){
$name=$_POST['name'];
$binders.=",$name";

$sql_update.="`name`=?";
}
...
if(isset($_POST['phone']) && $_POST['phone']!=''){
$phone=$_POST['phone'];
$binders.=",$phone";

$sql_update.="`phone`=?";
}
$binders = trim($binders, ',');
$sql_update = trim($sql_update, ',');


if ($sql_update!='' && $binders!='') {
$sql = "UPDATE ___table___
SET $sql_update
WHERE id=$___id___";
$q = $conn->prepare($sql);
// $q->execute(array($binders,$___id___));

}

How would you send it to the PDO function?

 

I spent the whole day trying to convert it from a mysql statement to a PDO statement, and feel like  :suicide:

Link to comment
Share on other sites

You need to put the parameters into an actual array, not a comma-separated string.

 

Probably the easiest approach is to assemble an associative array with the keys being the columns and the values being the values for the SET clause. You can then create your query from this array at the very end.

Link to comment
Share on other sites

  • Solution

Maybe something like the following...

<?php
$data=array();
$query='';
foreach(array('name','phone') as $key) {
    if(isset($_POST[$key]) && $_POST[$key]!=''){
        $data[$key]=$_POST[$key];
        $query.="$key=:$key,";
    }
}
if(!empty($data)){
    $sql = 'UPDATE myTable SET '.trim($query, ",").' WHERE id=:id';
    $data['id']=123;
    $q = $conn->prepare($sql);
    $q->execute($data);
}
  • Like 1
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.