2017-08-05 66 views
-3

連接:PHP創建一個表MySQL服務器(庫MySQLi)

<?php 
$db_name = "xxx"; 
$mysql_username = "xxx"; 
$mysql_password = "xxx"; 
$server_name = "xxx"; 
// Create connection 
$conn = new mysqli("xxx","xxx","xxx","xxx"); 
if ($conn->connect_error) { 
    die("Connection failed: " . $conn->connect_error); 
} 
echo "Connected successfully"; 
?> 

完整的代碼(這是登記的代碼)[編輯](我是越來越近了?):

<?php 
    require "conn.php"; 
    echo "debug 1"; 
    $stmt = $conn->prepare("SELECT * FROM UserData WHERE username = ?"); 
    $stmt->bind_param('s',$username); 
    $username = $_POST["username"]; 
    $stmt->execute(); 
    $stmt->store_result(); 

    echo "debug 2"; 
    if ($stmt->num_rows == 0){ // username not taken 
     echo "debug 3"; 
     $stmt2 = $conn->prepare("INSERT INTO UserData (username, password) VALUES (?, ?)"); 
     $password =($_POST["password"]); 
     $username =($_POST["username"]); 
     $stmt2->bind_param('ss', $username, $password); 
     $stmt2->execute(); 
     $MyServer = ($_POST["username"]); 
    $stmt3 = $conn->prepare('CREATE TABLE ? (
     id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, 
     username VARCHAR(30) NOT NULL 
     )'); 
    $stmt3->bind_param('s',$username); 
    $username = $_POST["username"]; 
    $stmt->execute(); 
    ///mysqli_query(connection object,query) 
     if ($stmt2->affected_rows == 1){ 
     echo 'Insert was successful.'; 

     }else{ echo 'Insert failed.'; 
     var_dump($stmt2); 
     } 
    }else{ echo 'That username exists already.';} 
    ?> 

我用這段代碼創建了一個包含發佈用戶名的表。這有什麼問題,因爲它不起作用。

+1

到目前爲止,您已經有了一個包含SQL語句的字符串。你在做什麼?我們需要您使用的代碼來運行查詢和您得到的錯誤。 – Nick

+0

把你用來執行你提到的查詢的代碼放在 –

+0

如何在MySQLi中執行查詢? (我是初學者,請具體說明) –

回答

0
$MyServer = ($_POST["username"]); 
$sql = "CREATE TABLE '$MyServer' (
    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, 
    username VARCHAR(30) NOT NULL 
    )"; 
$result = mysqli_query($con,$sql); 

mysqli_query(連接對象,查詢)

可以執行如上面查詢。

+0

這不起作用。 –

0

只是我個人的偏好。

$myServer = mysqli_real_escape_string($con, $_POST["username"]); 
$sql = "CREATE TABLE '$MyServer' (
    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, 
    username VARCHAR(30) NOT NULL 
    )"; 
$result = mysqli_query($conn, $sql); 

PDO也是一種選擇。

$host = 'localhost'; 
$db = '<INSERT DATABASE NAME HERE>'; 
$user = '<INSERT USERNAME HERE>'; 
$pass = '<INSERT PASSWORD HERE>'; 
$charset = 'utf8'; 

$dsn = "mysql:host=$host;dbname=$db;charset=$charset"; 

$pdo = new PDO($dsn, $user, $pass, $opt); 

$stmt = $pdo->prepare('CREATE TABLE ? (
     id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, 
     username VARCHAR(30) NOT NULL 
     )'); 
$stmt->execute([$myServer]); 
$success = $stmt->fetch(); 
0

使用以下行烏爾SQL vaiable

$sql = " create table if not exists {$MyServer} (
    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, 
    username VARCHAR(30) NOT NULL 
    )"; 

,並在表名的單引號(')的mysql是不是有它的`;