Note that there are some explanatory texts on larger screens.

plurals
  1. POPHP PDO with bindParam vs bindValue?
    primarykey
    data
    text
    <p><strong>SOLUTION</strong></p> <p>Change this:</p> <pre><code>foreach($fields as $dbfield =&gt; $field) { $value = isset($_POST[$field]) ? 1 : 0; $STH -&gt; bindParam( ':' . $dbfield, $value, PDO::PARAM_INT, 1 ); } </code></pre> <p>to this:</p> <pre><code>foreach($fields as $dbfield =&gt; $field) { $value = isset($_POST[$field]) ? 1 : 0; $STH -&gt; bindValue( ':' . $dbfield, $value, PDO::PARAM_INT ); } </code></pre> <hr> <p><strong>QUESTION</strong></p> <p>I have the following code, which doesn't give any errors, but it doesn't do what I need it to do:</p> <p><strong>PHP</strong></p> <pre><code>$fields = array( 'db_col_1' =&gt; 'cb_1', 'db_col_2' =&gt; 'cb_2', 'db_col_3' =&gt; 'cb_3' ); $parts = array(); foreach($fields as $dbfield =&gt; $field){ $parts[] = '`' . $dbfield . '` = :' . $dbfield; } $DBH = new PDO( "mysql:host=localhost;dbname=db", "user", "pass" ); $DBH -&gt; setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); //temp id $id = 1; $STH = $DBH -&gt; prepare( 'UPDATE `table1` SET ' . join(', ', $parts) . ' WHERE `id`= :id' ); $STH -&gt; bindParam( ':id', $id, PDO::PARAM_INT, 10 ); foreach($fields as $dbfield =&gt; $field) { $value = isset($_POST[$field]) ? 1 : 0; $STH -&gt; bindParam( ':' . $dbfield, $value, PDO::PARAM_INT, 1 ); } $STH -&gt; execute(); </code></pre> <p><strong>HTML</strong></p> <pre><code>&lt;input id="cb_1" name="cb_1" type="checkbox" value="cb_1" /&gt; &lt;br /&gt; &lt;input id="cb_2" name="cb_2" type="checkbox" value="cb_2" /&gt; &lt;br /&gt; &lt;input id="cb_3" name="cb_3" type="checkbox" value="cb_3" /&gt; </code></pre> <p>The database goes get updated, but if I check the checkboxes as follows:</p> <p><strong>SAMPLE CHECKBOX STATES</strong></p> <pre><code>cb_1 = 1 cb_2 = 1 cb_3 = 0 </code></pre> <p>Every column in the db gets <code>0</code>.</p> <p>If I check the checkboxes as follows:</p> <p><strong>SAMPLE CHECKBOX STATES</strong></p> <pre><code>cb_1 = 0 cb_2 = 0 cb_3 = 1 </code></pre> <p>Every column in the db gets <code>1</code>.</p> <p>Anyone know how to fix this?</p> <p>Could it be because <code>bindParam</code> binds the actual variable <code>$value</code> (by reference) which I think, by the time the loop ends, has a value based on <code>$_POST['cb_3']</code>?</p> <p>So I think I am supposed to be using <code>bindValue</code>? But not sure how.. I've checked the documentation, but find it confusing.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload