PHP Problemo - Newbie

Hey there.

I am new to PHP, and I thought it was time I started learning it. I’m good with HTML / CSS etc, but I need to learn PHP for Wordpress and creating plugins etc. I’ve got the basics alright, which most of the time I can BS my way out of it; although I’m planning to be learning it in depth this summer holidays. I’ve been messing around with MySQL and PHP lately and I’ve come across an error.

I’ve set up the database connection to make sure it gives me a Success or Failure error whenever it creates / doesn’t create the database. At the moment, it only shows the failure with the “The database (database name) wasn’t created; it already exists.”, although when I look in PHPMyAdmin the database was created successfully?

Here is my code:


<?php
	// Enter your MySQL Server Details and Creation Details here.
		$host = "localhost";
		$username = "root";
		$pass = "";
		$db = "localhost";
	// This connects to the Server, with a kill message.
		$connect = mysql_connect($host, $username, $pass);
		if (!$connect)
			{
				die("Could not connect to the server. ") . mysql_error() . (".") ;
			}
	// Create the Database with the details.
		mysql_query("CREATE DATABASE $db");
	// Messages for creation or failure.
		if (mysql_query("CREATE DATABASE $db", $connect))
			{
				echo("Success!");
			}
		else
			{
			echo("There was a problem creating the database. ") . mysql_error() . (".");
		}
		mysql_close($connect);
?>

Thanks to all in advance for the help. :slight_smile:

The problem you have here is this:


    // Create the Database with the details. 
        mysql_query("CREATE DATABASE $db"); 
    // Messages for creation or failure. 
        if (mysql_query("CREATE DATABASE $db", $connect)) 

Inside the if condition it’s not just testing whether the DB was created, it actually runs the query again - for the second time in your code - and then jumps to the true or false code block depending on the success or failure of that function.

All you have to do to fix this is remove this:

    // Create the Database with the details. 
        mysql_query("CREATE DATABASE $db"); 

Ah, brilliant. Thank you for the help. :slight_smile:

No problem. Keep in mind, running functions as conditions works with a most (not quite comfortable saying all) native php functions, and you can make it the case with your own using return statements.

You can even use conditions as a way to get lots of variable assignments done in a single line of code. I came up with a little trick I use a lot when grabbing data from a Database:

while($row = $results->fetch_assoc() and $row and $data[]=$row);

It’s not hard to see what happens here, once you have a result set, inside a while loop condition you get the row as a temporary variable, then test that row isn’t a falsey value (false, 0, empty string, empty array…) and finally drop it into the array. If any of those steps fail, the loop stops, thanks to the ‘and’ keyword.