Automatically creating new tables?

Hi.

I’m trying to add on to my news feature by creating a feedback form. I think in order to do this, I would need to come up with some code that would create a new table each time I submit news.

I checked w3schools, found some code and changed it around:


<?php
$con = mysql_connect("blah blah blah");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
  
// Create table
mysql_select_db("commentbox", $con);
$sql = "CREATE TABLE comment1

id int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id),
Date date,
Name varchar(30),
Message text
)";

// Execute query
mysql_query($sql,$con); 
?> 

(I’m not sure if the message and date ones are right so let me know if they need to be fixed).

Anyway, would it be possible to automatically create a new database without having to go in and rename “comment1” to “comment2” myself, but have it do that automatically?

Ok the code works to create a new table, but how do i automatically create a another one each time I visit this page? Is it possible to use a primary key from a different table?


<?php
$con = mysql_connect("blah blah blah");

mysql_select_db("commentbox", $con);
$sql = "CREATE TABLE Something
(
id int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id),
Name varchar(30),
Message text,
Date date
)";

// Execute query
mysql_query($sql,$con);

mysql_close($con);
?>

Why do you need a new table for each news post you make?

You can just have on comments table and link comments in it to news posts with a column called news_id.

How would I go about doing this exactly?

Sorry, I’m new to PHP.

CREATE TABLE comments
(
comment_id int NOT NULL AUTO_INCREMENT,
news_id int not null,
Name varchar(30),
Message text,
Date date,
PRIMARY KEY(id)
)

When someone makes a comment, insert a record in the comments table and put the ID for the news post in the news_id column.

Then when you need to get the comments for a specific news post, you select from the comments table “WHERE news_id=ID_FOR_POST”

Alright, I’m giving it a try.

I’m sorry, but what would the code be for this?

SELECT * FROM comments WHERE news_id=%NEWS_ID%

Substitute %NEWS_ID% for the news post ID number for which you want to fetch comments.

Kay, thanks :slight_smile:

Hrm doesn’t seem to work for me. It does post the comments, but they show up on all the articles.



<?php
  
("SELECT * FROM commentnews WHERE news_id=id");
 
 do {

echo $row_newscomment['Name']; echo "<br />";
echo $row_newscomment['Date']; echo "<br />";
echo $row_newscomment['Message'];

 } while ($row_newscomment = mysql_fetch_assoc($newscomment));

?>


I can see that you are a bit lost with PHP. I suggest you start with some tutorials.

This is a walk through for creating a news system with comments:

Thanks I am a bit lost lol. I’ll check that out.