Search code examples
phpmysqliprepared-statementcreate-table

Two query in mysqli prepared?


I am executing two queries in one mysqli connection, the first one is working fine, but the second one is not.

Here's code:

<?php
//from server
$con = mysqli_connect("localhost","user","pass","db");

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
?>


<?php

//mysqli prepare
$stmt = $con->prepare("INSERT INTO users_rooms (ip, rooms, description, date_time)
        VALUES (?,?,?, NOW())");
//bind params
$stmt->bind_param("sss", $ip, $rooms, $description);

    $trunc_text = substr($_POST['channel_description'], 0, 250);
    $rooms = preg_replace('/[^\w\d\s]+/', "", $_POST['channel_name']);
    $temp_rooms = str_replace(' ', '_', $rooms);
    $con->error;
    if(($trunc_text < 251) && isset($rooms)){

        //insert and execute msyqli
        $ip = $_SERVER['REMOTE_ADDR'];
        $rooms = mysqli_real_escape_string($con, htmlspecialchars(strip_tags($temp_rooms)));
        $description = mysqli_real_escape_string($con, htmlspecialchars(strip_tags($trunc_text)));
        $stmt->execute();
    }

//The above part of mysql is working fine, it's inserting the data as expected

//The below part of mysql is not working, it's not creating a table as $rooms

$rooms = mysqli_real_escape_string($con, htmlspecialchars(strip_tags($temp_rooms)));

$sql = "CREATE TABLE '$rooms' (
                        id BIGINT(255) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
                        ip VARCHAR(255) NOT NULL,
                        time VARCHAR(255) NOT NULL,
                        image_path VARCHAR(255),
                        smiley_path VARCHAR(255),
                        text_input VARCHAR(255),
                        current_date DATETIME
                        )";
$con->query($sql);
$con->error;
$stmt->close(); 
$con->close();
?>

Solution

  • You have error in your sql query, try below code

    $sql = "CREATE TABLE $rooms (
        `id` BIGINT(255) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        `ip` VARCHAR(255) NOT NULL,
        `time` VARCHAR(255) NOT NULL,
        `image_path` VARCHAR(255),
        `smiley_path` VARCHAR(255),
        `text_input` VARCHAR(255),
        `current_date` DATETIME
    )";