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...
Related
I am trying to create a "setup script" for my website. I would like to create the database, adding tables and some content at the same time. So far this is how I did it, but it seems kind off messy using multiple queries:
<?php
$servername = "localhost";
$username = "root";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Create database
$sql = "CREATE DATABASE MYDB";
if ($conn->query($sql) === TRUE) {
echo "1. Database created successfully <br/>";
$conn->select_db("MYDB");
$sql_members = "CREATE TABLE MEMBERS (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
USERNAME VARCHAR(30) NOT NULL,
EMAIL VARCHAR(40) NOT NULL,
DISCOUNT VARCHAR(5),
PASSW CHAR(128),
ROLE VARCHAR(9)
)";
if ($conn->query($sql_members) === TRUE) {
echo "2. Table MEMBERS created successfully <br/>";
} else {
echo "Error creating table: " . $conn->error;
}
$sql_content = "CREATE TABLE CONTENT (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
TITLE VARCHAR(30) NOT NULL,
TEXT VARCHAR(30) NOT NULL
)";
if ($conn->query($sql_content) === TRUE) {
echo "3. Table CONTENT created successfully <br/>";
} else {
echo "Error creating table: " . $conn->error;
}
} else {
echo "Error creating database: " . $conn->error;
}
$conn->close();
?>
Is there a better way?
Thanks!
== UPDATE ==
I have tried to export the database and use the resulted .sql file as my setup query, but something is wrong, I get:
Error creating tables: 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 'INSERT INTO CONTACTS (ID, NAME, PHONE,
EMAIL, ADDRESS, CITY, `COUN' at line 12
CREATE TABLE IF NOT EXISTS `CONTACTS` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`NAME` varchar(25) COLLATE utf8_romanian_ci NOT NULL,
`PHONE` varchar(16) COLLATE utf8_romanian_ci NOT NULL,
`EMAIL` varchar(35) COLLATE utf8_romanian_ci NOT NULL,
`ADDRESS` text COLLATE utf8_romanian_ci NOT NULL,
`CITY` varchar(16) COLLATE utf8_romanian_ci NOT NULL,
`COUNTRY` varchar(16) COLLATE utf8_romanian_ci NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_romanian_ci AUTO_INCREMENT=2 ;
INSERT INTO `CONTACTS` (`ID`, `NAME`, `PHONE`, `EMAIL`, `ADDRESS`, `CITY`, `COUNTRY`) VALUES
(1, 'Peter Brown', '0742062307', 'office#shop.com', 'Avenue 13.', 'Santaclaus', 'Austria');
== SOLUTUION ==
I needed "multi_query()" for executing my multiple queries.
You can try this too :p
$errors = [];
$table1 = "CREATE TABLE MEMBERS (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
USERNAME VARCHAR(30) NOT NULL,
EMAIL VARCHAR(40) NOT NULL,
DISCOUNT VARCHAR(5),
PASSW CHAR(128),
ROLE VARCHAR(9)
)";
$table2 = "CREATE TABLE CONTENT (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
TITLE VARCHAR(30) NOT NULL,
TEXT VARCHAR(30) NOT NULL
)";
$tables = [$table1, $table2];
foreach($tables as $k => $sql){
$query = #$conn->query($sql);
if(!$query)
$errors[] = "Table $k : Creation failed ($conn->error)";
else
$errors[] = "Table $k : Creation done";
}
foreach($errors as $msg) {
echo "$msg <br>";
}
You could export the whole database including all tables using the command line or using PhPMyAdmin. Then query the content of the file in php to create the database.
you can create a file and put all your sql queries in it..
CREATE TABLE MEMBERS (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
USERNAME VARCHAR(30) NOT NULL,
EMAIL VARCHAR(40) NOT NULL,
DISCOUNT VARCHAR(5),
PASSW CHAR(128),
ROLE VARCHAR(9)
);
CREATE TABLE CONTENT (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
TITLE VARCHAR(30) NOT NULL,
TEXT VARCHAR(30) NOT NULL
);
then in your php code:
$query = file_get_contents ('queries.sql');
if ($conn->query($query) === TRUE) {
echo "all tables created successfully <br/>";
} else {
echo "Error creating tables: " . $conn->error;
}
This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 6 years ago.
Can someone help me with that code, any directions welcome
I want every user who passed session to create table(every user creates own table -others cant see it).
<?php
session_start();
if($_SESSION['user']==''){
header("Location:login.php");
}else{
$dbh=new PDO('mysql:dbname=something;host=127.0.0.1', 'something', 'something');
$sql=$dbh->prepare("SELECT * FROM users WHERE id=?");
$sql->execute(array($_SESSION['user']));
while($r=$sql->fetch()){
$sql = "CREATE TABLE .'$r['username'].'" (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";
$conn->exec($sql);
echo " created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
}
}
?>
You can try to fix your php code and get something like this:
<?php
session_start();
if($_SESSION['user']==''){
header("Location:login.php");
}else{
$dbh=new PDO('mysql:dbname=something;host=127.0.0.1', 'something', 'something');
$sql=$dbh->prepare("SELECT * FROM users WHERE id=?");
$sql->execute(array($_SESSION['user']));
while($r=$sql->fetch()){
$sql = "CREATE TABLE `".$r['username']."` (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";
try {
$dbh->exec($sql);
echo " created successfully";
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
}
$conn = null;
}
?>
You have some error in your query string. You have one double quote you should remove, and the table name should be wrapped with ` instead of '. So your code should look like:
$sql = "CREATE TABLE `{$r['username']}` (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";
And even if its not really related to the topic you should ask yourself if create a table per user is the best solution.
I am trying to use my pi as a webserver. When I am attempting to create a Table in my database it is returning an internal server error. Can anyone try help me diagnose whats causing it?
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'anthony';
$dbname = "messages";
$conn = mysql_connect($dbhost, $dbuser, $dbpass, $dbname);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully<br />';
$sql = "CREATE TABLE IF NOT EXISTS message_tbl (
message_id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
message_name VARCHAR(50) NOT NULL,
message_subject VARCHAR(40) NOT NULL,
message_txt VARCHAR(500) NOT NULL,
message_amount INT(10) NOT NULL,
message_die VARCHAR(10) NOT NULL,
message_modifier INT(10) NOT NULL,
message_roll INT(10) NOT NULL
)";
mysql_select_db( 'TUTORIALS' );
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not create table: ' . mysql_error());
}
echo "Table created successfully\n";
mysql_close($conn);
?>
I would usually atleast expect it to come back with Could not create table:. I have installed apache2, php, and mysql with a database called messages on my pi.
MySQL's default port is 3306, not 3036. But you really should scrap that obsolete code and start fresh with PDO. Something like this might work. I'm on a device using the app so probably not my best work but should at least get you pointed in the right direction.
<?php
try {
$conn = new PDO("mysql:host=localhost;dbname=TUTORIALS", "root", "anthony");
echo 'Connected successfully<br />';
$sql = "CREATE TABLE IF NOT EXISTS message_tbl (
message_id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
message_name VARCHAR(50) NOT NULL,
message_subject VARCHAR(40) NOT NULL,
message_txt VARCHAR(500) NOT NULL,
message_amount INT(10) NOT NULL,
message_die VARCHAR(10) NOT NULL,
message_modifier INT(10) NOT NULL,
message_roll INT(10) NOT NULL
)";
$conn->query($sql);
echo "Table created successfully\n";
} catch (PDOException $e) {
die($e->getMessage());
}
?>
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();
}
?>
I've used this script to link to my database account (1&1), using Dreamweaver, which proves to be a successful connection yet cannot seem to create tables for my database when this is linked, was just wondering if anyone has any idea in how to go about the right way with this as I can't seem to get it working.
My database connection which works.
<?php
$hostname="db************";
$database="db********";
$username="db********";
$password="*********";
$link = mysql_connect($hostname, $username, $password);
if (!$link) {
die('Connection failed: ' . mysql_error());
}
else{
echo "Connection to MySQL server " .$hostname . " successful!
" . PHP_EOL;
}
$db_selected = mysql_select_db($database, $link);
if (!$db_selected) {
die ('Can\'t select database: ' . mysql_error());
}
else {
echo 'Database ' . $database . ' successfully selected!';
}
mysql_close($link);
?>
This is the tables script i'm using which doesn't work .
<?php
include_once("php_includes/db_conx.php");
// CREATE TABLE USER
$sql= "CREATE TABLE USER (
id_user_pk INT NOT NULL AUTO_INCREMENT,
nick VARCHAR(40),
email VARCHAR(40),
password VARCHAR(20),
user_reg_date DATE,
PRIMARY KEY (id_user_pk)
) TYPE=INNODB";
mysql_query($sql);
?>
You must use "ENGINE=INNODB" instead of "TYPE=INNODB";
CREATE TABLE `user` (
`id_user_pk` int(11) NOT NULL AUTO_INCREMENT,
`nick` varchar(40) DEFAULT NULL,
`email` varchar(40) DEFAULT NULL,
`password` varchar(20) DEFAULT NULL,
`user_reg_date` date DEFAULT NULL,
PRIMARY KEY (`id_user_pk`)
) ENGINE=INNODB;