0

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 "\n $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.

3
  • why dont you try to count if you get any rows? Commented May 8, 2014 at 1:20
  • $choices = mysqli_query("select * from " . $table); is returning false because you don't have your connection as the first parameter, so (!$choices) will return true. Try $choices = mysqli_query($connection, "select * from " . $table); Commented May 8, 2014 at 1:20
  • @Sean Adding $connection, fixed my error but if I removed the false parameter ! from the if statement it broke it again. I'll mark an answer explaining this as correct if you give it. Commented May 8, 2014 at 1:32

2 Answers 2

1

I would recommend using the PHP function mysqli_num_rows($choices) and changing if statement to:

if(mysqli_num_rows($choices) == 0) {

If you print_r the $choices variable as it is currently written, you will probably see that it is not empty. There was no error... There just were no rows returned. What you want to know is not if there was an error, but if there were any rows returned.

Sign up to request clarification or add additional context in comments.

2 Comments

Changing mysqli_query("select * from " . $table); to mysqli_query($connection, "select * from " . $table); also fixes the problem. Is this a better solution? Why or why not, and how does it work?
I chalk it up to personal preference, but I could be wrong. Whatever works and is consistent!
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.