Creating a dynamic table in MySql using PHP - php

Im trying to create tables in mysql dynamically in php
$usernametable="test".$usname;
$create = ("CREATE TABLE $usernametable(
id SMALLINT NOT NULL PRIMARY KEY,
test1 SMALLINT, test2 SMALLINT, test3 SMALLINT )");
$createtable = mysql_query($create, $conn)
or die ('Problem with query' . mysql_error());
It doesnt seem to work and i dont even get an error message. What seems to be the problem?

Try this it is working for me
$con = mysql_connect(<host>,<username>,<password>) or die(mysql_error());
mysql_select_db(<database_name>,$con);
$usernametable="test".$usname;
$create = ("CREATE TABLE $usernametable(
id SMALLINT NOT NULL PRIMARY KEY,
test1 SMALLINT, test2 SMALLINT, test3 SMALLINT )");
$createtable = mysql_query($create, $con)
or die ('Problem with query' . mysql_error());

Related

Failing to create mySQL table

I'm trying to create a table if it does not already exist in my database. For this I'm running this test which is working as intended:
$conn = mysql_connect("localhost", "twa222", "twa222bg");
mysql_select_db("airline222", $conn) or die ("Database not found " . mysql_error() );
$val = mysql_query("SELECT 1 from '$FLIGHTID'");
However my problem comes when I try to create the table itself, which is giving me the following error:
Problem with query: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''passenger' SMALLINT NOT NULL, 'booking' CHAR(6), 'seat' VARCHAR(3))' at line 2
This is the code that is attempting to generate the table
if(!$val)
{
$sql = "CREATE TABLE ".$FLIGHTID." (
passenger SMALLINT NOT NULL PRIMARY KEY,
booking CHAR(6), seat VARCHAR(3) )";
$rs = mysql_query($sql) or die ("Problem with query" . mysql_error());
}
mysql_close($conn);
I originally thought it was the ".$FLIGHTID." that was causing the problem but when I changed that to simply be ABC I still got the same error.
Can anyone see where I am going wrong?
EDIT:
My SQL output when using ABC is:
CREATE TABLE ABC ( passenger SMALLINT NOT NULL PRIMARY KEY, booking CHAR(6), seat VARCHAR(3) )
Without using ABC it is:
CREATE TABLE ( passenger SMALLINT NOT NULL PRIMARY KEY, booking CHAR(6), seat VARCHAR(3) )
You use single quotes arround column names what is not allowed. Single qoutes indicates that the value inside is a litaral:
Change:
$val = mysql_query("SELECT 1 from '$FLIGHTID'");
to:
$val = mysql_query("SELECT 1 from $FLIGHTID");
Use mysqli_*or PDOinstead of deprecated mysql_* API.

Javascript image slider doesnt work

I get the "Table creation success" message but no table is created.
<html>
<body>
<?php
$con=mysql_connect("localhost","root","");
//create db
mysql_query("CREATE DATABASE VashDedomenwn2", $con);
echo "Db creation success <br>";
//create table
$sql= mysql_query("CREATE TABLE VashDedomenwn2.phone_book
(
personID int NOT NULL,
PRIMARY KEY(person ID),
LastName varchar(20) NOT NULL,
FirstName varchar(20),
Address varchar(30),
Age int,
Phone varchar(10)
)
");
mysql_query($sql,$con);
echo "Table creation success <br>";
//END CONNECTION
mysql_close($con);
?>
</body>
</html>
I'm a newbie in php! Probably it's a stupid mistake... Thanks fot the help
Before you create a table, you must open the database you created.
//create db
mysql_query("CREATE DATABASE VashDedomenwn2", $con);
echo "Db creation success <br>";
mysql_select_db("database name", $con);
//create table
...
And change
$sql= mysql_query("CREATE TABLE VashDedomenwn2.phone_book
(
...
)
");
to
$sql= mysql_query("CREATE TABLE `VashDedomenwn2.phone_book`
(
...
)
");
OK, as #php_purest said, use mysqli is better. Mysqli is the improved version of mysql which support OOPS. It can reduce the pressure of your server.
Like this:
$conn = new mysqli("localhost","root","");
$conn->query("CREATE DATABASE VashDedomenwn2");
echo "Db creation success <br>";
$conn->select_db("VashDedomenwn2");
//create table
$conn->query("CREATE TABLE `VashDedomenwn2.phone_book`
(
personID int NOT NULL PRIMARY KEY,
LastName varchar(20) NOT NULL,
FirstName varchar(20),
Address varchar(30),
Age int,
Phone varchar(10)
)
");
echo "Table creation success <br>";
//END CONNECTION
$conn->close();

PHP and MySQL Foreign key not working as expected

I'm doing a bit of MySQL using commands through PHP only (without using the phpMyAdmin interface to create the tables) and I'm having a bit of a problem creating Primary and Foreign keys. This is my current code.
<?php
$conectar = mysql_connect("localhost", "root", "") or die (mysql_error());
//mysql_query("CREATE DATABASE DataBaseTeste") or die(mysql_error());
mysql_select_db("DataBaseTeste") or die(mysql_error());
mysql_query("CREATE TABLE Pergunta("
. "id_Pergunta INT AUTO_INCREMENT,"
. "Descricao TEXT,"
. "Nivel VARCHAR,"
. "PRIMARY KEY(id_Pergunta),"
. "FOREIGN KEY(id_Assunto) REFERENCES Assunto(id_Assunto))")Or die(mysql_error());
mysql_query("CREATE TABLE Aluno("
. "id_Aluno INT NOT NULL,"
. "AlunoNome CHAR,"
. "Grupo CHAR,"
. "PRIMARY KEY(id_Aluno))")Or die(mysql_error());
mysql_query("CREATE TABLE Assunto("
. "id_Assunto INT,"
. "Descricao VARCHAR,"
. "PRIMARY KEY(id_Assunto))")Or die(mysql_error());
mysql_close();
?>
I also tried using this (without the FOREIGN KEY, by just inserting the other table's id):
$conectar = mysql_connect("localhost", "root", "") or die (mysql_error());
//mysql_query("CREATE DATABASE DataBaseTeste") or die(mysql_error());
mysql_select_db("DataBaseTeste") or die(mysql_error());
mysql_query("CREATE TABLE Pergunta("
. "id_Pergunta INT AUTO_INCREMENT,"
. "Descricao TEXT,"
. "Nivel VARCHAR,"
. "PRIMARY KEY(id_Pergunta),"
. "id_Assunto INT)")Or die(mysql_error());
The error message I get is this:
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'PRIMARY KEY(id_Pergunta)..."
It's probably something pretty stupid but I can't figure it out.
First, try to use lowercase names, I just did it for PKs
Then to use foreign keys you must add the column name do that table which will hold the FK
Also then, you need to use INNODB, can't remember if MyIsam allows you FK, but I recommend it, note that INNODB will create an index for them too.
CREATE TABLE assunto(
id_assunto INT,
descricao VARCHAR(254),
PRIMARY KEY(id_assunto)
)ENGINE=INNODB;
CREATE TABLE aluno(
id_aluno INT NOT NULL,
alunoNome CHAR(254),
grupo CHAR,
PRIMARY KEY(id_aluno)
)ENGINE=INNODB;
CREATE TABLE pergunta(
id_pergunta INT AUTO_INCREMENT,
id_assunto int,
descricao TEXT,
nivel VARCHAR(254),
PRIMARY KEY(id_pergunta),
FOREIGN KEY(id_assunto) REFERENCES assunto(id_assunto)
)ENGINE=INNODB;
Let me add you a PHP version, note the execution order.
<?php
$conectar = mysql_connect("localhost", "root", "") or die (mysql_error());
//mysql_query("CREATE DATABASE DataBaseTeste") or die(mysql_error());
mysql_select_db("DataBaseTeste") or die(mysql_error());
mysql_query("CREATE TABLE aluno("
. "id_aluno INT NOT NULL,"
. "alunoNome CHAR,"
. "grupo CHAR,"
. "PRIMARY KEY(id_aluno))")Or die(mysql_error());
mysql_query("CREATE TABLE assunto("
. "id_assunto INT,"
. "descricao VARCHAR,"
. "PRIMARY KEY(id_assunto))")Or die(mysql_error());
mysql_query("CREATE TABLE Pergunta("
. "id_pergunta INT AUTO_INCREMENT,"
. "id_assunto INT AUTO_INCREMENT,"
. "descricao TEXT,"
. "Nivel VARCHAR,"
. "PRIMARY KEY(id_pergunta),"
. "FOREIGN KEY(id_assunto) REFERENCES assunto(id_assunto))")Or die(mysql_error());
mysql_close();
This is a working sqlfiddle Mysql 5.1, I use 5.5.32 but show as 5.1 will work too.
http://sqlfiddle.com/#!8/f88b5/3

Create 2nd tables and add data

I have this task from school, and I am confuse and lost on how I got to do this.
So basically I have to create 2 tables to the database but I have to created from php.
I have created the first table, but not the second one for some reason.
And then, I have to populate first and second tables with 10 and 20 sample records respectively, populate, does it mean like adding more fake users? if so is it like the code shown below?
*I got error on the populating second part as well
Thank you so much for the help.
<?php
$host = "host";
$user = "me";
$pswd = "password";
$dbnm = "db";
$conn = #mysqli_connect($host, $user, $pswd, $dbnm);
if (!$conn)
die ("<p>Couldn't connect to the server!<p>");
$selectData = #mysqli_select_db ($conn, $dbnm);
if(!$selectData)
{
die ("<p>Database Not Selected</p>");
}
//1st table
$sql = "CREATE TABLE IF NOT EXISTS `friends`
(
`friend_id` INT NOT NULL auto_increment,
`friend_email` VARCHAR(20) NOT NULL,
`password` VARCHAR(20) NOT NULL,
`profile_name` VARCHAR(30) NOT NULL,
`date_started` DATE NOT NULL,
`num_of_friends` INT unsigned,
PRIMARY KEY (`friend_id`)
)";
//2nd table
$sqlMyfriends = "CREATE TABLE `myfriends`
(
`friend_id1` INT NOT NULL,
`friend_id2` INT NOT NULL,
)";
$query_result1 = #mysqli_query($conn, $sql);
$query_result2 = #mysqli_query($conn, $sqlMyfriends);
//populating 1st table
$sqlSt3="INSERT INTO friends (friend_id, friend_email, password, profile_name, date_started, num_of_friends)
VALUES('NULL','email#email.com','123','abc','2012-10-25', 5)";
$queryResult3 = #mysqli_query($dbConnect,$sqlSt3)
//populating 2nd table
$sqlSt13="INSERT INTO myfriends VALUES(1,2)";
$queryResult13=#mysqli_query($dbConnect,$sqlSt13);
mysqli_close($conn);
?>
The others have addressed one of your issues, so this is in relation to not being able to add values to your tables (populate). Your connection link is $conn -
$conn = #mysqli_connect($host, $user, $pswd, $dbnm);
ie.
$query_result1 = #mysqli_query($conn, $sql);
but when you are adding your values to the tables, you changed your connection link to $dbConnect
...
$queryResult3 = #mysqli_query($dbConnect,$sqlSt3)
...
$queryResult13=#mysqli_query($dbConnect,$sqlSt13);
To insert multiple values into your table you could add a comma and additional parentheses ,() -
//populating 2nd table
$sqlSt13="INSERT INTO myfriends VALUES(1,2),(2,3),(3,1)";
$queryResult13=#mysqli_query($conn,$sqlSt13);
Or you could use mysqli_multi_query, and list each one-
//populating 2nd table
$sqlSt13 ="INSERT INTO myfriends VALUES (1,2);";
$sqlSt13 .="INSERT INTO myfriends VALUES (2,3);";
$sqlSt13 .="INSERT INTO myfriends VALUES (3,1);";
$queryResult13=#mysqli_query($conn,$sqlSt13);
see the manual for mysqli_multi_query - php.net/manual/en/mysqli.multi-query.php
You have an extra comma here that might cause an error:
friend_id2 INT NOT NULL,
should be:
$sqlMyfriends = "CREATE TABLE `myfriends` (
`friend_id1` INT NOT NULL,
`friend_id2` INT NOT NULL
)";
I wish I could be at school now :)
You have the following errors in code:
1) $queryResult3 = #mysqli_query($dbConnect,$sqlSt3)
Is correct: $queryResult3 = #mysqli_query($dbConnect,$sqlSt3);
2) $sqlMyfriends = "CREATE TABLE myfriends
(
friend_id1 INT NOT NULL,
friend_id2 INT NOT NULL,
)";
Is correct: $sqlMyfriends = "CREATE TABLE myfriends
(
friend_id1 INT NOT NULL,
friend_id2 INT NOT NULL)";
3) $queryResult3 = #mysqli_query($conn,$sqlSt3);
Is correct: $queryResult3 = mysqli_query($conn,$sqlSt3);
Code correct is:
Couldn't connect to the server!");
$selectData = #mysqli_select_db ($conn, $dbnm);
if(!$selectData)
{
die ("Database Not Selected");
}
//1st table
$sql = "CREATE TABLE IF NOT EXISTS `friends`
(
`friend_id` INT NOT NULL auto_increment,
`friend_email` VARCHAR(20) NOT NULL,
`password` VARCHAR(20) NOT NULL,
`profile_name` VARCHAR(30) NOT NULL,
`date_started` DATE NOT NULL,
`num_of_friends` INT unsigned,
PRIMARY KEY (`friend_id`)
)";
//2nd table
$sqlMyfriends = "CREATE TABLE `myfriends`
(
`friend_id1` INT NOT NULL,
`friend_id2` INT NOT NULL
)";
$query_result1 = #mysqli_query($conn, $sql);
$query_result2 = #mysqli_query($conn, $sqlMyfriends);
//populating 1st table
$sqlSt3="INSERT INTO friends (friend_id, friend_email, password, profile_name, date_started, num_of_friends)
VALUES('NULL','email#email.com','123','abc','2012-10-25', 5)";
$queryResult3 = mysqli_query($conn,$sqlSt3);
//populating 2nd table
$sqlSt13="INSERT INTO myfriends VALUES(1,2)";
$queryResult13=#mysqli_query($dbConnect,$sqlSt13);
mysqli_close($conn);
?>
I hope to help !

users and posts database issue

Is it true that after a user signs up, a sql table is create for him to store his posts ?
I make it similar in mysql after the man insert him into my page. The database is the same name with but the table name is made when he log in first time.
class Users
{
var $username="root";
var $password="pass";
var $database="InsertIntoStackOverflow";
var $table_name="";
public function Users($username)
{
$table_name=$username."_tb";
echo $table_name."<br/>";
mysql_connect(localhost,$username, $password) or die("unable to connect to database ".mysql_error());
echo $database."<br/>";
mysql_selectdb($database) or die("unable to select db ".mysql_error());
$query="CREATE TABLE ".$table_name." (id tinyint(4) NOT NULL AUTO_INCREMENT, title VARCHAR(128) NOT NULL, date_post VARCHAR(100), date_edit VARCHAR(100), post_content TEXT NOT NULL)";
mysql_query($query) or die("Unable to create table. ".mysql_error());
}
}
But it display only table_name and an error, the database name not display. Error is NO DATABASE IS SELECTED/
EDIT
This class is call after he sign up
I also have a function postApost but when I do
ob_start();
session_start();
require("Users_DB.php");
$name=$_SESSION['user'];
echo 'Welcome '.$name;
$username=new UserDB($name);
there is no table created
Two variables with same name $username. Use $this for accessing variable of class. Missing quote(") with localhost - it must be string type parameter. and this code can't create table on Database because you use AUTO_INCREMENT on your code but forgot to mention that as a PRIMARY KEY. I think the following code help you a lot.
class Users
{
var $username="root";
var $password="pass";
var $database="InsertIntoStackOverflow";
var $table_name="";
function __construct($user_name)
{
$this->table_name=$user_name."_tb";
echo $this->table_name."<br/>";
mysql_connect("localhost",$this->username, $this->password) or die("unable to connect to database ".mysql_error());
echo $this->database."<br/>";
mysql_selectdb($this->database) or die("unable to select db ".mysql_error());
$query="CREATE TABLE ".$this->table_name." (id tinyint(4) NOT NULL AUTO_INCREMENT, title VARCHAR(128) NOT NULL, date_post VARCHAR(100), date_edit VARCHAR(100), post_content TEXT NOT NULL, PRIMARY KEY (id))";
mysql_query($query) or die("Unable to create table. ".mysql_error());
}
}
And you can use this class by the following way :
$clsName = new Users('username');
Create one table:
CREATE TABLE Posts (
id TINYINT(4) NOT NULL AUTO_INCREMENT,
user VARCHAR(20) NOT NULL,
title VARCHAR(128) NOT NULL,
date_post DATETIME,
date_edit DATETIME,
post_content TEXT NOT NULL
)
Inserting new posts:
$insert = "
INSERT INTO Posts (
user,
title,
date_post,
date_edit,
post_content
) VALUES (
'$username',
'$title',
NOW(),
NOW(),
'$post_content'
)
";
Updating is simple:
$update = "
UPDATE Posts SET
title = '$title',
post_content = '$post_content',
date_edit = NOW()
WHERE id = '$postid';
";
Get all posts for user:
$posts = "
SELECT title, date_post, date_edit, post_content
FROM Posts
WHERE user = '$username'
ORDER BY date_post
";

Categories