Question

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");

?>
Was it helpful?

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());

OTHER TIPS

Was just a couple of syntax issues... see below.. just tested and successfully created the table. Let me know if any problems.

<?php

$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");
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top