Note that there are some explanatory texts on larger screens.

plurals
  1. PODynamic query building from POST data in PHP
    text
    copied!<p>I have large tables in my database and instead of specifying each column name I am trying to build the query dynamically.</p> <p>I am trying to do an update in the 'motherboard' table based on the POST data received. The <code>$data</code> object i receive has more fields than the table has. (I added some fields for some flags.) Hence, I am retrieving the record I'm about to update and by comparing each of it's columns with my <code>$data</code> object fields I am constructing the UPDATE query.</p> <p>I'm new to php, therefore I don't know the syntax well.</p> <p>This is the code:</p> <pre><code>&lt;?php $data = json_decode($_POST["data"], true); $id = $data["ID"]; include_once 'dbconnect.php'; $query = sprintf("SELECT * FROM `motherboard` WHERE ID = " . $id . ";"); $result = mysqli_query($con, $query); $existingData = mysqli_fetch_assoc($result); include_once 'dbclose.php'; $statement = ""; $statement = "UPDATE motherboard SET "; $flag = false; foreach ($existingData as $key =&gt; $value) { if ($existingData-&gt;$key != $data-&gt;$key) { $statement .= $key . " = " . $data-&gt;$key . " , "; $flag = true; } } if ($flag) $statement = substr($statement, 0, strrchr($statement, ',') - 1); $statement .= " WHERE ID = " . $id . ";"; echo $statement; ?&gt; </code></pre> <p>My main problem is in the <code>foreach</code> loop. I don't know how can I compare and then use for building the query the <code>$existingData</code> and <code>$data</code> variables. </p> <p>How can I achieve this?</p>
 

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