mysqli_query不能在php中工作

时间:2017-12-12 16:15:26

标签: php html mysql

我正在尝试使用php和phpmyadmin创建一个寄存器。我有帖子工作,并将数据插入表格也有效。这条线的作用是什么..

 $result = mysqli_query($conn, $sql);

我尝试使用以下代码调试它,但没有出现错误。这是我的register.php文件。

require_once('config1.php');

if(!$conn):
die('Connect Error (' . mysqli_connect_errno() . ') '. 
mysqli_connect_error());
endif;

if(isset($_POST) && !empty($_POST)) {
    $username = $_POST['username'];
    $email = $_POST['email'];
    $password = $_POST['password'];

    $sql = "INSERT INTO 'zz_login' (username, email, password) VALUES ('$username', '$email', '$password')";
    $result = mysqli_query($conn, $sql);
    if($result) {
        echo "user registration successful";
    } else {
        mysqli_error($conn);
    }
}
;

这是我的配置文件

error_reporting(E_ALL);
ini_set('display_errors', '1');

$conn = mysqli_connect("localhost", "username", "password", "database"); 
if (!$conn) {
die("could not connect" . mysqli_connect_error($conn));
}

不确定有什么问题,真的很感激一些帮助。提前致谢。

2 个答案:

答案 0 :(得分:2)

看起来你有一个sql-error而你忘记了mysqli_error前面的echo命令,试试这个:

if($result) {
    echo "user registration successful";
} else {
   echo mysqli_error($conn);
}

答案 1 :(得分:0)

你应该使用pdo,它更好,请遵循以下代码:

// define config options, you can save this code into one file and require it

$config = [
	'username' => 'root',
	'password' => '',
	'database' => 'site'	
];

// make a connnection function for easily accessing it
function connect($config)
{
	try{
		$conn = new \PDO('mysql:host=localhost;dbname=' .$config['database'], $config['username'], $config['password']);

		$conn->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);

		return $conn;
	} 
	catch(Exception $e){
		return false;
	}

}// end connect()

// this is the query function, at bottom I'll show how to use
function query($query, $bindings, $conn)
{
	$stmt = $conn->prepare($query);
	$stmt->execute($bindings);

	return ($stmt->rowCount() > 0) ? $stmt : false ;
}


// Usage

// require
require 'databases.php';

// Connect to the db
$conn = connect($config);

if ( !$conn ) die("Could not connect.");

// define an array for status
$data = [];

if($_SERVER['REQUEST_METHOD'] === 'POST') {
    // get needed form
    $username = $_POST['username'];
    $email = $_POST['email'];
    $password = $_POST['password'];
    
    // here mysql queries, any of them, super easy and secured
    query(
      "INSERT INTO zz_login(username, email, password) 
       VALUES (:username, :email, :password"),[
        'username' => $username,
        'email' => $email,
        'password' => $password
       ],
       $conn);
    // status array
    $data['status'] = "user registration successful";
    } else {
       $data['status'] = 'Failure';
        
        if ($data) {
			    extract($data);
		    }
    }
}