Search code examples
phpmysqldatabaseconnectionmamp

PHP "database could not connect" MAMP


I'm trying to use php to add a table to a database I created in MAMP.

I have explored these answers here:
Cannot connect to mysql server with MAMP nor with Community Server
Connect to MySQL in MAMP

I have also tried using this code on a server, this free hosting site called. biz.nf. There I get no connection error, but the table is not created.

Really stumped here, would appreciate any advice, thanks.

<?php

$con = mysql_connect("localhost:3306", "paul", "paul");
mysql_select_db("magusblog", $con);

$table = "ENTRIES";
mysql_query("CREATE TABLE IF NOT EXISTS '$table' ( 'ID' INT NOT NULL AUTO_INCREMENT , PRIMARY KEY ( 'ID' ) )");
mysql_query("ALTER TABLE '$table' ADD 'PHOTO' TEXT NOT NULL");
mysql_query("ALTER TABLE '$table' ADD 'TITLE' TEXT NOT NULL");
mysql_query("ALTER TABLE '$table' ADD 'DATE' TEXT NOT NULL");
mysql_query("ALTER TABLE '$table' ADD 'CONTENT' TEXT NOT NULL");

?>

Solution

  • All of your queries have syntax errors. You do NOT use ' quotes to delimit field names. If you'd bothered actually CHECKING if errors were occuring, you'd have been informed about this:

    CREATE TABLE IF NOT EXISTS '$table' ( 'ID' INT NOT NULL AUTO_INCREMENT , PRIMARY KEY ( 'ID' ) )
                               ^--    ^-- ^--^---                                          ^--^-
    

    remove ALL of the indicated quotes, on ALL of your queries. And then rewrite them as:

    $result = mysql_query(...) or die(mysql_error());