我的mqsql_query函数不起作用

时间:2013-09-01 15:16:48

标签: php mysql

我刚开始使用PHP。 我目前正在为我的网页制作登录脚本。 当我尝试运行mysql_query(SELECT * FROM users WHERE username=$username)时 它不起作用。 我确定我使用了正确的名字, 但我一直有查询功能的问题。 这是我的代码,有没有人看到这个问题?

<?php

$username = $_POST['username'];
$password = $_POST['password'];

if ($username&&$password)
{
    $connect = mysql_connect("host", "dbname", "password!") or die ("Couldnt connect!");
    mysql_select_db("TwoogLogin") or die ('couldnt find datebase');

    $query = mysql_query("SELECT * FROM users WHERE username=$username") or die ('unable to run query');

    $numrows = mysql_num_rows($query);

    echo $numrows;
}
else
    die("Please enter a username and a password");
?>

3 个答案:

答案 0 :(得分:1)

尝试这种方式:

<?php
$username = $_POST['username'];
$password = $_POST['password'];

if ($username!=='' && $password!==''){
$connect = mysql_connect("host", "dbname", "password!");
if (!$connect)
  {
  die('Could not connect: ' . mysql_error());
  }

$db_selected = mysql_select_db("TwoogLogin",$connect);
if (!$db_selected)
  {
  die ("Cannot use TwoogLogin: " . mysql_error());
  }

$query = "SELECT * FROM users WHERE username='$username'";
$numrows = mysql_query($query,$connect);
echo mysql_num_rows($numrows);

mysql_close($connect);
}else{
echo "Please enter a username and a password";
}
?>

根据以下评论(@Pascamel)msql_*扩展程序的建议,PHP 5.5.0已弃用,并且将来会被删除。相反,应使用MySQLiPDO_MySQL扩展名。

<?php
$username = $_POST['username'];
$password = $_POST['password'];


if ($username!=='' && $password!==''){
$connect = mysqli_connect("host", "dbname", "password!");
if (!$connect)
  {
  die('Could not connect: ' . mysqli_error());
  }

$db_selected = mysqli_select_db("TwoogLogin",$connect);

$query = "SELECT * FROM users WHERE username='$username'";
$numrows = mysqli_query($query,$connect);
echo mysqli_num_rows($numrows);

mysqli_close($connect);
}else{
echo "Please enter a username and a password";
}
?>

答案 1 :(得分:0)

<?php
//Set appropriate value for the following statements
$connect = mysql_connect("mysql_server", "mysql_user", "mysql_password") or die ("Couldnt connect!");
mysql_select_db("database_name",$connect) or die ('couldnt find datebase');


$username = $_POST['username'];
$password = $_POST['password'];

if ($username && $password)
{
    $query = mysql_query("SELECT * FROM users WHERE username='$username'") or die ('unable to run query');

    $numrows = mysql_num_rows($query);

    echo $numrows;
}
else
    die("Please enter a username and a password");
?>

答案 2 :(得分:-1)

查询中的语法错误!你应该使用username ='$ username' 另一个原因是关于列的错误名称你确定列的名称是对的吗?