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();
Related
I wanted to add New table in my database and this table should have 5 columns but it should be done by filling up a form in the website Let's say I'm going to add Travel Order table with it's five columns. Now i have this code in my form and it gives me this error: Call to undefined method mysqli::mysqli_real_escape_string()
<input type="text" class="form-control1" onKeyPress= "return lettersOnly(event)" name= "categoryname" id="categoryname" placeholder="Category Name..." maxlength="30" reqiured> this for the table name.
<input type="text" class="form-control1" onKeyPress= "return lettersOnly(event)" name="firstattrib" id="firstattrib" placeholder="..." maxlength="30"> this for one of the column. (please don't mind my naming of variables)
`
$connect = mysqli_connect("localhost","root","","doctrack_db");
// Check connection
if ($connect->connect_error) {
die("Connection failed: " . $connect->connect_error);
}
// sql to create table
$sql = "CREATE TABLE ".$categoryname." (
id INT(6) UNSIGNED AUTO_INCREMENT NOT NULL,
file LONGBLOB(30) NOT NULL,
)";
$firstattrib = $connect->mysqli_real_escape_string($_POST['firstattrib']);
//query to add columns to table
$query = 'ALTER TABLE ' .$categoryname . '
ADD COLUMN '. $firstattrib .' VARCHAR(30) TINYINT NOT NULL DEFAULT \'0\' AFTER file';
if ($connect->query($sql)&$connect->query($query) === TRUE) {
echo "alert('Category created successfully!!')";
} else {
echo "alert('Error creating Category!!')" . $connect->error;
}
$connect->close();
?>`
Can you please tell me which part i got wrong or is it wrong as a whole?
try this
<?php
// Create connection
mysql_connect("localhost","root","","test") OR die("Server Connection error");
mysql_select_db("test") OR die("DB error");
$category = "category";
// sql to create table
$sql = "CREATE TABLE ".$category." (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";
if(mysql_query($sql)){
$sql1 = "INSERT INTO ".$category." (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
mysql_query($sql1);
}
?>
and it doesn't matter when you create table, what matter is when you inserting data into table have to has exist.
This is my code http://prntscr.com/a2d8qq currently, I am learning things but I am really wondering why it will say that there is no database selected, tho I have selected it in line 5, also if I remove the "dbname = users_details" and then execute a query that creates a databse then it is fine. But whenever I create a table in that database (I selected it) it will not make me, I searched across google and it really is the same to my code but mine will not work.
<?php
try {
$connect = new PDO("mysql: host = 'localhost'; dbname = users_details", 'root', '');
$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sqlQuery = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";
$connect->exec($sqlQuery);
echo 'Successfully created table.';
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>
So this fixed my problem: I have to execute a query to use a specified database into where I want my tables to be in. Then in the line 5 I have just removed the "dbname =
<?php
try {
$connect = new PDO("mysql: host = 'localhost';", 'root', '');
$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sqlQuery = "CREATE TABLE details (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";
$connect->exec("use users_details");
$connect->exec($sqlQuery);
echo 'Successfully created table.';
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>
This is what I have so far.... I do not understand why it is not working? Any ideas? This is just a simple script to connect to a database, create a table and insert some data. I also want to retrieve the data but I think I may be jumping a little a head.
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
$link = mysql_connect('localhost', 'root', '');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
if (mysql_query("CREATE_DATABASE nogjhghkgst98", $link))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
if ($link="CREATE TABLE contactsZ8 (id int(6) NOT NULL auto_increment,first varchar(15) NOT NULL,last varchar(15) NOT NULL,phone varchar(20) NOT NULL,mobile varchar(20) NOT NULL,fax varchar(20) NOT NULL,email varchar(30) NOT NULL,web varchar(30) NOT NULL,PRIMARY KEY (id),UNIQUE id (id),KEY id_2 (id))") {
echo "ineserted";
}
else
{
echo "not inserted" . mysql_error();
}
$link = "INSERT INTO contactsZ VALUES ('','John','Smith','01234 567890','00112 334455','01234 567891','johnsmith#gowansnet.com','http://www.gowansnet.com')";
$link="SELECT * FROM contactsZ";
$link=mysql_query($link);
mysql_close($link);
?>
There is definitely something wrong:
if ($link="CREATE TABLE contactsZ8 (id int(6) NOT NULL auto_increment,first varchar(15) NOT NULL,last varchar(15) NOT NULL,phone varchar(20) NOT NULL,mobile varchar(20) NOT NULL,fax varchar(20) NOT NULL,email varchar(30) NOT NULL,web varchar(30) NOT NULL,PRIMARY KEY (id),UNIQUE id (id),KEY id_2 (id))") {
an assignment in an if
query not executed (that is not so bad: once the table is created, executing again the query when reloading the page will fail)
assigning to $link ! this is confusing (but should not generate any error)...
Then :
$link = "INSERT INTO contactsZ VALUES ('','John','Smith','01234 567890','00112 334455','01234 567891','johnsmith#gowansnet.com','http://www.gowansnet.com')";
The query is not executed.
Edit: the INSERT is done in contactsZ, whereas the CREATE TABLE creates contactsZ8.
Edit2: And finally:
mysql_close($link);
After re-assigning 3 times $link, $link is not the (optional, by the way) link identifier any more...
Probably a simple overlook, but I cannot seem to create a table with my PHP script. My first question is that I want to add a table to an existing DB. How do I tell the server which DB to create the table in? The code to create a table is pretty simple, but here it is ..
CREATE TABLE Countr(ID INT IDENTITY(1,1) PRIMARY KEY,Page VARCHAR(50),
Month INT, Always INT);
Any assistance would be appreciated.
In your PHP server you should be connecting to your database. Your code might be like this:
mysqli_connect("sqlserver.mysite.com", "username", "password") or die("SQL Error: Cant connect to database.");
Then you should do:
mysqli_select_db("database_name") or die("SQL Error: Cant select database");
to select the database before performing any other sql statements. Such as creating tables.
http://dev.mysql.com/doc/refman/5.0/en/use.html
USE my_db1;
CREATE TABLE ...
USE my_db2;
CREATE TABLE ...
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
mysql_select_db('database_name', $link);
CREATE TABLE Countr(ID INT IDENTITY(1,1) PRIMARY KEY,Page VARCHAR(50), Month INT, Always INT);
Try this code to create table in any database.
CREATE TABLE db_name.Countr(ID INT IDENTITY(1,1) PRIMARY KEY,Page VARCHAR(50), Month INT, Always INT);
Note: Current database user has create table privileges in the other database.
$sql = "CREATE TABLE wp_shifts (
user_id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
transact_id int(64),
hours decimal(10,2),
date varchar(64),
time1 varchar(64),
PRIMARY KEY (user_id)
)";
$results = $wpdb->query($sql);
Create a Table
The CREATE TABLE statement is used to create a table in MySQL.
We must add the CREATE TABLE statement to the mysqli_query() function to execute the command.
The following example creates a table named "Persons", with three columns: "FirstName", "LastName" and "Age":
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Create table
$sql="CREATE TABLE Persons(FirstName CHAR(30),LastName CHAR(30),Age INT)";
// Execute query
if (mysqli_query($con,$sql))
{
echo "Table persons created successfully";
}
else
{
echo "Error creating table: " . mysqli_error($con);
}
?>
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
";