I am building a SQL query using the following foreach loop:
$sql = "UPDATE table01 SET ";
foreach(array_combine($values, $variables) as $value=>$variable)
{
$sql .="$value = $variable,";
}
$sql = rtrim($sql,',');
$sql .=" WHERE id = '$id'";
$values is an array of field titles to be updated (column headers in db) while $variables is an array of variables containing the data.
An example of the query built by such a loop is here:
UPDATE table01
SET sv_21 = 123, sv_22 = 123, sv_23 = 2011, sv_I8 = 1 sachet every day, sv_I9 = 3
WHERE id = '001'
SQL of recognises “every day” as syntax and it breaks the update command.
How can I enter this data in ? In reality these queries are usually much larger and several strings cause syntax errors.
Thanks for your consideration
If it is relevent, here is the PDO I am using to execute the UPDATE:
try
{
$pdo = new PDO('mysql:host=localhost; dbname=tables', $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare($sql);
$stmt->execute();
# Affected Rows?
echo $stmt->rowCount(); // 1
}
Whenever you enter text data (as opposed to numerical data) into an SQL field, you need to put it in quotes. For example:
Some types of SQL, such as MySQL, will let you put any data in quotes, so you should update your PHP to work like this:
Before you do this, however, you should know that this is a dangerous way to use your database. If a user were to put an apostrophe (
') into their data, then they could add their own SQL command into your database. This is called SQL injection, and its one of the leading ways that websites get hacked.A safer way to update your database would be to write the full SQL statement, with placeholders, and explicitly define the value for each placeholder. You can learn more about this method here:
http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/