如何创建两个查询mysql insert和create table

时间:2017-09-27 08:46:08

标签: php mysql sql database mysqli

我想创建两个查询,一个用于将数据输入一个表,另一个用于创建新表。这是我创建新表但不插入数据的代码。我哪里错了?谢谢。

$sql = "INSERT INTO progetti(data, ora, nome_progetto)VALUES('".$_POST["data"]."','".$_POST["ora"]."','".$_POST["nome_progetto"]."')";

          "CREATE TABLE $_POST[nome_progetto] (
            id INT(11) AUTO_INCREMENT PRIMARY KEY,
            data date,
            intervento varchar(30),
            descrizione varchar(70),
            ore int(2)
          )";

2 个答案:

答案 0 :(得分:1)

在这里你可以创建if else语句,如果插入完成则创建将运行

<?php

/*
* These are Database Credentials
*/
    $servername = "localhost";
    $username = "root";
    $password = " ";
    $dbname = "test_db";

    /*
    * Intiating the Database connection
    */
    $conn = new mysqli($servername, $username, $password, $dbname);

    /*
    * Checking the Databse connection
    */
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } 

     $create = "CREATE TABLE ".$_POST[nome_progetto]." (
                    id INT(11) AUTO_INCREMENT PRIMARY KEY,
                    data date,
                    intervento varchar(30),
                    descrizione varchar(70),
                    ore int(2))";
            $result = $conn->query($create);     

    if ($result === TRUE) {
     $sql = "INSERT INTO progetti(data, ora, nome_progetto)VALUES('".$_POST["data"]."','".$_POST["ora"]."','".$_POST["nome_progetto"]."')";

      $insert = $conn->query($sql); 
      if ($insert === TRUE) {
        echo "New record created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }

    }


    $conn->close();
    ?>

答案 1 :(得分:0)

  1. 使用不同的SQL语句(在您的情况下为2,一个用于插入,另一个用于create table)
  2. 使用PHP中的抽象层(PDO)提供的准备语句
  3. 阅读SQL Injection