PHP从数组中生成sql脚本


PHP making sql script from array

我用php创建了一个数组。阵列如下:

array(37) {
  [0]=>
  array(2) {
    ["title"]=>
    string(43) "first title"
    ["images"]=>
    array(4) {
      [0]=>
      string(57) "images/pathtiimage1.jpg"
      [1]=>
      string(57) "images/pathtoimage2.jpg"
      [2]=>
      string(57) "images/pathtoimage3.jpg"
      [3]=>
      string(57) "images/pathtoimage4.jpg"
    }
  }
  [1]=>
  array(2) {
    ["title"]=>
    string(61) "second title"
    ["images"]=>
    array(4) {
      [0]=>
      string(71) "images/pathtoimage1.jpg"
      [1]=>
      string(71) "images/pathtoimage2.jpg"
      [2]=>
      string(71) "images/pathtoimage3.jpg"
      [3]=>
      string(71) "images/pathtoimage4.jpg"
    }
  }
 etc.

我的目标是将这些数据插入数据库,是否可以为此创建一个sql脚本,或者直接从我创建这个数组的同一页中执行?

编辑我的数据库应该是这样的a表显然带有id和标题的产品由于一个产品可以具有多个图像,所以第二表对每个图像具有唯一的id和正确的产品id。

我还做了这个数组的json_encode的回声,可能有用吗?

当然可以这样做,因为所有框架(PHP或任何其他语言)都这样做是为了防止直接运行SQL命令。

但这并不是那么容易。你需要以一种通用的方式来处理它。您必须指定相关的表。例如,你可以有这样的模型:

class Product extends Model {
    $relations = array(
        'has_many' => array(
            'Image' => array(
                'foreign_key' => 'product_id',
            ),
        ),
    );
}
class Image extends Model {
    $relations = array(
        'belongs_to' => array(
            'Product' => array(
                'foreign_key' => 'product_id',
            ),
        ),
    );
}

我从laravel、CakePHP等PHP框架和其他框架中获得了这个想法。

但是我不建议您实现所有这些东西,而您可以使用经过测试的、当然可靠的已实现框架。

最好使用一些框架或它们作为框架做事的方式。。但若您正在尝试了解如何生成查询(字符串),下面的代码可能会有所帮助。但这不是一种首选的方式。。。。

$ary = array (
    array 
    (
        "title"=> "first title",
            "images"=> array 
            (
            "images/pathtiimage1.jpg",
            "images/pathtoimage2.jpg",
            "images/pathtoimage3.jpg",
            "images/pathtoimage4.jpg"
                )
    ),
    array 
    (
    "title"=> "second title",
        "images"=> array 
            (
                "images/pathtoimage1.jpg",
                "images/pathtoimage2.jpg",
                "images/pathtoimage3.jpg",
                "images/pathtoimage4.jpg"
                )
    )
);
// Read array
foreach($ary as $product)
{
    // Generate query insert into proudcts (product_title) values($product["title"])..
    // Execute query...
    // get saved product id in same variable $product_id
    // read images array
    foreach ($product["images"] as $image)
    {
        // assign product_id to images table referrence key....
        // Generating sql insert query use $images to get value..
        // execute query
    }
}
?>