如何将数组中的数据直接保存到数据库中?用PHP

时间:2011-07-05 18:26:31

标签: php sql arrays

例如:

array('u_ad'=>'example name','u_mail'=>'example@mail.com','u_sifre'=>'exapmlepass')

必填查询:

$sql = "INSERT INTO uyeler 
          (u_ad,u_mail,u_sifre) 
        VALUES 
          ('example name','example@mail.com','examplepass')";

我是怎么做到的?

3 个答案:

答案 0 :(得分:2)

$sql = "INSERT INTO uyeler (". implode(",", array_keys($array)) .") VALUES ('". implode("','", $array) ."')";

答案 1 :(得分:1)

快/脏/不安全:

$sql = "INSERT INTO uyeler (u_ad,u_mail,u_sifre) VALUES ('" . $theArray['u_ad'] . "','" . $theArray['u_mail'] . "','" . $theArray['u_sifre'] . "')";

更好:

$ad = mysql_real_escape_string($theArray['u_ad']);
$mail = mysql_real_escape_string($theArray['u_mail']);
$sifre = mysql_real_escape_string($theArray['u_sifre']);

$sql = "INSERT INTO uyeler (u_ad,u_mail,u_sifre) VALUES ('" . $ad . "','" . $mail . "','" . $sifre . "')";

答案 2 :(得分:1)

不要随意逃跑!您应该尽可能使用prepared statements,并且使用PDO是一种很好的方法。

请参阅:

Why you Should be using PHP’s PDO for Database Access
ext/mysqli: Part I - Overview and Prepared Statements