dongxilan9351 2014-05-08 00:57
浏览 58
已采纳

PHP if语句没有正确检测MySQL表

I have two PHP documents. One that connects to my MySQL server and database (it will also create the database if it doesn't exist). This document is titled "db_connect.php". My next PHP document is titled "create.php" and it is designed to connect to a specific table within the database and create that table if it doesn't exist. There's also a javascript document involved in this which makes it so the user can type things and enter them into the table without the page being refreshed. I don't think you'll need this document and so I won't include it, but I thought you guys might find it helpful to know that this is for a message board.

Here's my db_connect.php file:

<?php
    $db = "my_db";
    //establish a connection with the server
    $connection = mysqli_connect('localhost', 'root', 'password');
    if(!$connection){
        exit("<p>Could not establish a connection :" . mysqli_connect_error() . "</p>");
    }
    //connect to the database
    $dbSelect = mysqli_select_db($connection, $db);
    if(!$dbSelect){
        // Create database
        $sql="CREATE DATABASE " . $db;
        if (mysqli_query($connection, $sql)) {
        } else {
          echo "<p>Error creating database: " . mysqli_error($connection) . "</p>";
        }
    }
?>

Here's my create.php file:

<?php
//connect to the database
include('db_connect.php');
$table = 'NDI';
//update the table if the notes are posted
if(isset($_POST['notes'])){
    $notes=$_POST['notes'];
    $name=$_POST['name'];
    $file = $_POST['file'];
    $file2 = $_FILES['file'];
    echo "<p>Hello $file $file2</p>";
    /////////////////////////////////////////////
    //Check for file type
    /////////////////////////////////////////////
    if ((($_FILES["file"]["type"] == "image/gif")
        || ($_FILES["file"]["type"] == "image/png")
        || ($_FILES["file"]["type"] == "image/x-png")
        || ($_FILES["file"]["type"] == "image/jpeg")
        || ($_FILES["file"]["type"] == "image/jpg")
        || ($_FILES["file"]["type"] == "image/pjpeg")
        || ($_FILES["file"]["type"] == "application/x-shockwave-flash")
        )
        && ($_FILES["file"]["size"] < 999000)){
        /////////////////////////////////////////////
        //Check for errors
        /////////////////////////////////////////////
        if ($_FILES["file"]["error"] > 0){
            echo "Error: " . $_FILES["file"]["error"] . "<br />";
        }else{
        ///////////////////////////////////////////
        //Set the upload
        ///////////////////////////////////////////

            echo "Upload: " . $_FILES["file"]["name"] . "<br />";
            echo "Type: " . $_FILES["file"]["type"] . "<br />";
            echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
            echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
            /////////////////////////////////////////////////////////
            //Check to see if file exists already
            /////////////////////////////////////////////////////////
            if (file_exists("../uploads/" . $_FILES["file"]["name"])){
                //echo $_FILES["file"]["name"] . " already exists. ";
                $_FILES["file"]["name"] =  rand(1, 1000).$_FILES["file"]["name"];
            }
            ////////////////////////////////////////////////////////////
            //If not, move to the upload folder
            ////////////////////////////////////////////////////////////
            $path = '../uploads/';
            $tmp_name = $_FILES["file"]["tmp_name"][$key];
            $fn = basename( $_FILES['file']['name']); 
            move_uploaded_file($_FILES['file']['tmp_name'], $path.$fn);
            //move_uploaded_file($_FILES["file"]["tmp_name"],
            //"../uploads/" . $_FILES["file"]["name"]);
            echo "Stored in: ../uploads/". $_FILES["file"]["name"];
            $myImg =    "../uploads/" . $_FILES['file']['name'];
                //echo "
 $myImg";
        }
        //echo "<a href=../uploader/>Back</a>";
    }else{
        echo "Invalid file";
        //echo $_FILES["file"]["type"];
    }
    if(!$myImg){
        $myImg="../uploads/blank.png";
    }
    if(!$name){
        $name="anonymous";
    }
    $sql= "INSERT INTO `$table` SET `name` = '$name', `notes`='$notes', `img`='$myImg'";
    if (mysqli_query($sql)) {
        echo '<p>Entry added</p>';
        echo '<p><a href="index.php">' . $title . ' Home</a> </p>';
    } else {
        echo '<p>Error adding page: ' . mysqli_error() . '</p>';
    }
}
    //display results
$choices = mysqli_query("select * from " . $table);
if(!$choices){
    // Create table
    $sqlc="CREATE TABLE $table(`id` INT(5) AUTO_INCREMENT, `img` VARCHAR(50), `name` VARCHAR(25), `notes` TEXT(500), PRIMARY KEY (`id`))";

    // Execute query
    if (mysqli_query($connection, /*$db,*/ $sqlc)) {
    } else {
      echo "Error creating table: " . mysqli_error($connection/*, $db*/);
    }
}
while($row = mysqli_fetch_array($choices)){
    $img=$row['img'];
    $note=$row['notes'];
    $name=$row['name'];
    echo "<p class='note'><img src='$img'><span class='name'>$name: </span>$note</p>";
}
?>

The problem I'm running into is that the page echos the error: "Error creating table: Table 'NDI' already exists" so my if statement if(!$choices) is returning true. This if statement is supposed to return false when the table already exists. I can't figure out what's wrong with it. Any feedback you guys could give would be greatly appreciated.

  • 写回答

2条回答 默认 最新

  • dpr81047 2014-05-08 01:38
    关注

    You were missing your $connection as the 1st parameter of mysqli_query -> $choices = mysqli_query("select * from " . $table);.

    It should be -

    //display results
    $choices = mysqli_query($connection, "select * from " . $table);
    if(!$choices){
     ...
    }
    

    You want to keep ! in if(!$choices) as now you are properly checking if your query failed/returned 0 rows, as mysql table $table does not exist.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么