简体   繁体   中英

Insert sql statement in php Error: No database selected

So I'm attempting to make a registration form. I've made a php MySQL class which uses the constructor to make the connection with new MySQLi() for verifyLogin function and mysql_connect() for my addElement function.

The error is with my addElement function, the SQL statement writes out properly but it doesn't seem to connect to the database. I've checked that all the names are correct. Any ideas?

<?php

class MySQL {

private $connection;
private $conn;
private $databaseName;

function __construct($dbServer, $dbUser, $dbPassword, $dbName) {
    $this->connection = new MySQLi($dbServer, $dbUser, $dbPassword, $dbName)
        or die('PROBLEM CONNECTING TO DATABASE');

    $this->conn = mysql_connect($dbServer, $dbUser, $dbPassword);
        echo $this->conn;

    $databaseName = $dbName;
}

function verifyLogin($table, $email, $password) {

    $query = "SELECT *
            FROM ?
            WHERE email = ?
            AND password = ?
            LIMIT 1";

    if($statement = $this->connection->prepare($query)) {
        $statement->bind_param('sss', $table, $email, $password);
        $statement->execute();

        if($statement->fetch()) {
            $statement->close();
            return true;    
        }
        else {
            return false;
        }
    }

}

function addElement($table, $firstName, $lastName, $email, $mobile, $password,
                        $faculty, $campus) {


    $query = "INSERT INTO $table (first_name, last_name, email, mobile, password, faculty, campus_location) 
            VALUES('$firstName', '$lastName','$email','$mobile',
            '$password','$faculty','$campus');";
    echo $query;

    mysql_select_db($this->databaseName, $this->conn);

    if(!mysql_query($query)) {
        die('Error: ' . mysql_error()); 
    }

    mysql_close($this->connection);
}


}

?>

To select a database in MySQLi, you need to select it like so:

$db = new mysqli("localhost", "my_user", "my_password", "database_name");

or

$db = new mysqli("localhost", "my_user", "my_password");
$db->select_db('database_name');

as opposed to MySQL:

$db = mysql_connect('localhost', 'my_user', 'my_password');
$db_selected = mysql_select_db('database_name', $db);

MySQLi : http://www.php.net/manual/en/mysqli.select-db.php

MySQL : http://www.php.net/manual/en/function.mysql-select-db.php

You are mixing the mysql and the mysqli php drivers.

Since the mysql driver is deprecated I would suggest going with the mysqli.

PHP Documentation: http://www.php.net/manual/en/book.mysqli.php

Good Overview to get you started: http://www.dreamincode.net/forums/topic/54239-introduction-to-mysqli-and-prepared-statements/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM