已建立MySQL连接但查询失败

时间:2017-12-07 06:06:49

标签: php mysql

我正在尝试创建一个登录页面。 连接成功但查询未获取所需结果。 登录页面通过post方法将数据发送到action_page.php。

Action_page.php

<?php
$servername = "localhost:3306";
$username = "root";
$password = "";
$dbname = "MyDB";

$con = mysqli_connect($servername, $username, $password, $dbname);

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

$uname = $_POST['uname'];
$pass = $_POST['psw'];
$sql = "SELECT * FROM Users WHERE uname=".$uname." AND pass=".$pass;
echo "<br/>$sql<br/>";

//$result = $con->query($sql);

echo var_dump($con->query($sql));

$con->close();

This is my database.&GT;

有人可以帮忙。!

3 个答案:

答案 0 :(得分:2)

You can use single quote for the inserted variable inside double quote :)

$sql = "SELECT * FROM Users WHERE uname='$uname' AND pass='$pass'";

答案 1 :(得分:1)

更新
$sql = "SELECT * FROM Users WHERE uname=".$uname." AND pass=".$pass;

$sql = "SELECT * FROM Users WHERE uname='".$uname."' AND pass='".$pass."'";

答案 2 :(得分:1)

  

建议使用mysqli或PDO_MySQL扩展。它   不建议使用旧的mysql扩展进行新开发,   因为它在PHP 5.5.0中已被弃用,并在PHP 7中被删除。

示例您的代码与三个MySQL API比较

<?php
// mysqli
$mysqli = new mysqli("example.com", "user", "password", "database");
$result = $mysqli->query("SELECT * FROM Users WHERE uname='".$uname."' AND pass='".$pass."'");
$row = $result->fetch_assoc();
echo htmlentities($row['uname']);

// PDO
$pdo = new PDO('mysql:host=example.com;dbname=database', 'user', 'password');
$statement = $pdo->query("SELECT * FROM Users WHERE uname='".$uname."' AND pass='".$pass."'");
$row = $statement->fetch(PDO::FETCH_ASSOC);
echo htmlentities($row['uname']);

// mysql
$c = mysql_connect("example.com", "user", "password");
mysql_select_db("database");
$result = mysql_query("SELECT * FROM Users WHERE uname='".$uname."' AND pass='".$pass."'");
$row = mysql_fetch_assoc($result);
echo htmlentities($row['uname']);
?>

check link