Jump to content
Sign in to follow this  
Q695

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

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:

Share this post


Link to post
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.

Share this post


Link to post
Share on other sites

I tried assigning variable names first, but for some reason I was unable to get it process, so I decided to try with ? to get them to run.  Can you provide a run-able example?

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
Share on other sites

Thanks, that worked perfectly

Edited by Q695

Share this post


Link to post
Share on other sites

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.

Sign in to follow this  

×
×
  • 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.