Re: Escaping quotes
| From: | Tom Rogers | Date: | Thu, 12 Aug 2004 02:34:30 +0000 |
| Subject: | Re: Escaping quotes | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-193525@lists.php.net to get a copy of this message | ||
Hi,
Thursday, August 12, 2004, 10:03:32 AM, you wrote:
AH> Hi All,
AH> I have this expression;
AH> $query = "INSERT INTO $table (%s) VALUES (%s)";
AH> $query = sprintf($query, implode(",", $fld), implode(",",
AH> $val));
AH> $result = mssql_query($query) or die($errmsg);
AH> I am trying to insert values from an array into the database.
AH> I keep getting the error that I can't pass column names in this context.
AH> I know it's because I'm not enclosing $val in quotes.
AH> I've tried a number of variations;
AH> implode("\"","\"", $val)
AH> implode("\',\'", $val)
AH> implode(",", "\"".$val."\"") - This blows up nicely
AH> ;-)
AH> Where am I going wrong on this?
AH> alex hogan
You can do it this way but you must make sure that any strings in your
values array have been escaped before with mysql_escape_string() and
probably trimmed as well.
$fields = array('id','name','age');
$values = array(1,'Dave',40);
$table = 'test';
$sql = sprintf("INSERT INTO %s (%s) VALUES
('%s')",$table,implode(',',$fields),implode("','",$values));
echo $sql;
(It's perfectly ok to quote numbers)
--
regards,
Tom