简单的php / mysql无法正常工作

时间:2011-09-28 20:10:48

标签: php mysql

我在php脚本中有以下内容。我得到的是一个空白页面,没有错误或没有。

error_reporting(E_ALL);
ini_set("display_errors", 1);
$database = "mydatabase";
$con = mysql_connect("localhost", "admin", "password") or die(mysql_error());
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
$db = mysql_select_db($database);
if(!$db){
    die('Could not connect: ' . mysql_error());
}
if(isset($_POST['id'])){
$userid = mysql_real_escape_string($_POST['id']);
echo($userid);  
}
if(isset($_POST['name')){
$username = mysql_real_escape_string(htmlentities($_POST['name'])); 
echo($username);
}

$query = mysql_query("SELECT * FROM userinfo  
WHERE userid ='$userid'")or die(mysql_error()); 
if(mysql_num_rows($query) > 0){
    echo "yeah";
}else{
$query = mysql_query("INSERT INTO userinfo (username,userid)
VALUES ($username,$userid)")or die(mysql_error());
if(mysql_affected_rows($query)== 1){
echo "UPDATED";

}else{
    echo "NOPE";
}
}

2 个答案:

答案 0 :(得分:2)

您的SQL中也有错误:

INSERT INTO userinfo (username,userid)
VALUES ($username,$userid)

此处的值应引用:

INSERT INTO userinfo (username,userid)
VALUES ('$username', '$userid')

答案 1 :(得分:2)

您应该更好地格式化代码。你也错过了这一行的关闭括号,如果(isset($ _ POST ['Name')){

<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
$database = "mydatabase";
$con = mysql_connect("localhost", "admin", "password") or die(mysql_error());

if (!$con)
{
    die('Could not connect: ' . mysql_error());
}

$db = mysql_select_db($database);
if(!$db)
{
    die('Could not connect: ' . mysql_error());
}

if(isset($_POST['id']))
{
    $userid = mysql_real_escape_string($_POST['id']);
    echo($userid);  
}

if(isset($_POST['name']))
{
    $username = mysql_real_escape_string(htmlentities($_POST['name'])); 
    echo($username);
}

$query = mysql_query("SELECT * FROM userinfo WHERE userid ='$userid'")or die(mysql_error()); 
if(mysql_num_rows($query) > 0)
{
    echo "yeah";
}
else
{
    $query = mysql_query("INSERT INTO userinfo (username,userid) VALUES ($username,$userid)")or die(mysql_error());
    if(mysql_affected_rows($query)== 1)
    {
        echo "UPDATED";
    }
    else
    {
        echo "NOPE";
    }
}
?>