PHP PDO, connecting to database/selecting database + execute - php

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

Related

users storing own data . Mysql table name taken from session variable [duplicate]

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.

Error performing sql query in PHP

I am trying to learn using mysql in php. I started off trying to create a table in mysql, and using the mysqli extension.
My code:
<?php
$truemsg = "Table created successfully";
$falsemsg = "Error creating table: ";
$servername = "localhost";
$username = "myuser";
$password = "mypass";
$db = "mytable";
// Create database
$sql = "USE ".$db.";".
'CREATE TABLE IF NOT EXISTS Authentication (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
userid VARCHAR(30) NOT NULL,
password VARCHAR(30) NOT NULL,
role VARCHAR(20) NOT NULL,
email VARCHAR(50)
);';
print "Sql command is ".$sql;
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
print "<p></p>";
if ($conn->query($sql) === TRUE) {
echo $truemsg;
} else {
echo $falsemsg . $conn->error;
}
$conn->close();
?>
The error is:
Sql command is USE mytable;CREATE TABLE IF NOT EXISTS Authentication ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, userid VARCHAR(30) NOT NULL, password VARCHAR(30) NOT NULL, role VARCHAR(20) NOT NULL, email VARCHAR(50) );
Error creating table: 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 'CREATE TABLE IF NOT EXISTS Authentication ( id INT(6) UNSIGNED AUTO_INCREMENT PR' at line 1
I tried pasting the same command on the mysql command line, and it works fine. What's the problem using this in php?
You are supposed to run queries one by one
$sql = "query one";
$conn->query($sql);
$sql = 'query two';
$conn->query($sql);
instead of coupling them all in one statement.
DO NOT use mysqi_multi_query() either, this asynchronous function is not intended for the everyday use.
Also, in this particular case USE query is superfluous. Database should go into constructor:
$conn = new mysqli($servername, $username, $password, $db);
^^^ here
Also, tell mysqli to throw errors by itself, automatically, instead of checking result of every database command manually:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
This way you will get neat and clean code:
<?php
$servername = "localhost";
$username = "myuser";
$password = "mypass";
$db = "mytable";
// Create data table
$sql = 'CREATE TABLE IF NOT EXISTS Authentication (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
userid VARCHAR(30) NOT NULL,
password VARCHAR(30) NOT NULL,
role VARCHAR(20) NOT NULL,
email VARCHAR(50)
)';
// Create connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli($servername, $username, $password, $db);
// Run a query
$conn->query($sql);
echo "Table created successfully";
This code will either report that table has been created successfully, or emit an error, with a detailed explanation on what went wrong.
This seems to be like a mysql multiple query problem
$conn->select_db($db);
you can use this function before the query to use the database and remove the use database statement from your query string , then you query string becomes
$sql = 'CREATE TABLE IF NOT EXISTS Authentication (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
userid VARCHAR(30) NOT NULL,
password VARCHAR(30) NOT NULL,
role VARCHAR(20) NOT NULL,
email VARCHAR(50)
)';
that may work for you ..

Error in Table creation through PDO

<?php
require_once 'dbconfig.php';
try{
$dsn = "mysql:host=$host;dbname=$dbname"; // $dbname is empdb as in dbconfig.php
$dbh = new PDO($dsn, $username, $password);
$sql_create_dept_tbl = <<<EOSQL
CREATE TABLE departments(
department_no int(11) NOT NULL AUTO_INCREMENT,
name varchar(255) DEFAULT NULL,
PRIMARY KEY (department_no)
) ENGINE=InnoDB
EOSQL;
$sql_create_emp_tbl = <<<EOSQL
CREATE TABLE employees (
employee_no int(11) NOT NULL AUTO_INCREMENT,
first_name varchar(40) NOT NULL,
last_name varchar(40) NOT NULL,
department_no int(11) DEFAULT NULL,
PRIMARY KEY (employee_no),
KEY emp_dept (department_no),
CONSTRAINT emp_dept FOREIGN KEY (department_no)
REFERENCES departments (department_no)
) ENGINE=InnoDB
EOSQL;
$msg = '';
$r = $dbh->exec($sql_create_dept_tbl);
if($r !== false){
$r = $dbh->exec($sql_create_emp_tbl);
if($r !== false){
$msg = "Tables are created successfully!<br/>";
}else{
$msg = "Error creating the employees table.<br/>";
}
}else{
$msg = "Error creating the departments table.<br/>";
}
// display the message
if($msg != '')
echo $msg;
}catch (PDOException $e){
echo $e->getMessage();
}
I have gone through all the initialization still all I get is
"Error creating the departments table."
But I see a "departments" table already created in the database (empdb).
Why am I getting an error message when the table is already created?? . I am using WAMP server and phpMyadmin to access the database.
Any help regarding this will be of utmost value to me.
Add CREATE TABLE [IF NOT EXISTS] to your table definitions:
CREATE TABLE IF NOT EXISTS departments(
department_no int(11) NOT NULL AUTO_INCREMENT,
name varchar(255) DEFAULT NULL,
PRIMARY KEY (department_no)
) ENGINE=InnoDB
and:
CREATE TABLE IF NOT EXISTS employees
...
You are getting error because your table is already created and can`t be created again, so:
$r = $dbh->exec($sql_create_dept_tbl) // result is false
so below chunk of code getting printed
}else{
$msg = "Error creating the departments table.<br/>";
}
you can check if table already exists and run creation or skip it:
$result = $pdo->query("SELECT 1 FROM $table_name LIMIT 1");
if($result){
//// skip table creation
} else {
//// run table creation script
$r = false;
}
You cannot create a table with same name more than once . It's always a good practice to check whether the table already exist or not . Use this it will help you ,
CREATE TABLE [IF NOT EXISTS] table name

Simple PHP/MySQL Create Table Script

So I have this script just to create a table in my database. I've copied it over from an old script I did that is working right now. How come this one is not working? Anyone?
The error I am getting is "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 "'= varchar (20) NOT NULL, column_two = int NOT NULL auto_increment, column_thre' at line 2"
<?php
include("server_connect.php");
mysql_select_db("assignment5");
$create = "CREATE TABLE tbltable (
column_one = varchar (20) NOT NULL,
column_two = int NOT NULL auto_increment,
column_three = int NOT NULL,
column_four = varchar (15) NOT NULL,
column_five = year,
PRIMARY KEY = (column_one)
)";
$results = mysql_query($create) or die (mysql_error());
echo "The tables have been created";
?>
Remove all = as already suggested:
$create = "CREATE TABLE tbltable (
column_one varchar (20) NOT NULL,
column_two int NOT NULL auto_increment PRIMARY KEY,
column_three int NOT NULL,
column_four varchar (15) NOT NULL,
column_five year
)";
Each and every table should have a primary key and you must specify AUTO_INCREMENT column as PRIMARY KEY. In this case, the AUTO_INCREMENT column is column_two and I've set that as the PRIMARY KEY.
MySQLi Procedural
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// sql to create table
$sql = "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
)";
if (mysqli_query($conn, $sql)) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
(PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// sql to create table
$sql = "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
)";
// use exec() because no results are returned
$conn->exec($sql);
echo "Table MyGuests created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
The solution is to assign all the privileges to the BD user, like this:
GRANT ALL PRIVILEGES ON *. * TO 'user_name' # 'localhost';

Attempting to create a database and table and insert some data

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...

Categories