I have the following PHP page to create a table using a text file.
table_create.php
<?php
include $db;
$query_file = "sql.txt";
$fp = fopen($query_file, 'r');
$sql = fread($fp, filesize($query_file));
fclose($fp);
$retval = mysql_query($sql);
if(! $retval )
{
die("Could not create the tables<br>");
}
echo "Table created successfully<br>";
?>
sql.txt
CREATE TABLE ht_account (
id int(11) NOT NULL AUTO_INCREMENT,
date date NOT NULL,
type varchar(50) NOT NULL,
mode varchar(50) NOT NULL,
party varchar(50) NOT NULL,
payee varchar(50) NOT NULL,
rate decimal(13,2) NOT NULL,
box int(11) NOT NULL,
amount decimal(13,2) NOT NULL,
token varchar(50) NOT NULL,
remarks varchar(50) NOT NULL,
user varchar(50) NOT NULL,
user_confirm varchar(50) NOT NULL,
status varchar(50) NOT NULL);
CREATE TABLE ht_bank (
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(50) NOT NULL,
ac_no varchar(50) NOT NULL,
address varchar(50) NOT NULL);
CREATE TABLE ht_user_role (
id int(11) NOT NULL AUTO_INCREMENT,
value varchar(50) NOT NULL);
When I try to create a single table in the sql.txt file, the code works perfectly.
For example:
CREATE TABLE ht_account (
id int(11) NOT NULL AUTO_INCREMENT,
date date NOT NULL,
type varchar(50) NOT NULL,
mode varchar(50) NOT NULL,
party varchar(50) NOT NULL,
payee varchar(50) NOT NULL,
rate decimal(13,2) NOT NULL,
box int(11) NOT NULL,
amount decimal(13,2) NOT NULL,
token varchar(50) NOT NULL,
remarks varchar(50) NOT NULL,
user varchar(50) NOT NULL,
user_confirm varchar(50) NOT NULL,
status varchar(50) NOT NULL);
But when I try to create multiple tables, It does not create any table. I doubt that the format in the sql.txt may be incorrect.
The format is, almost sure, correct but mysql_query doesn't work with multiple queries:
mysql_query() sends a unique query (multiple queries are not
supported) to the currently active database on the server that's
associated with the specified link_identifier.
It's better to use mysqli functions because mysql ones are deprecated for PHP 5.5 and mysqli has the function mysqli_multi_query that you need.
If you still want to use mysql functions you could do something like:
$sql_array=explode(';',$sql);
foreach ($sql_array as $s) {
if(! mysql_query($s)){
echo mysql_error()."<br>";
}
}
Related
How to use if not exists in MySQL database.
create schema if not exists appkasir;
use appkasir;
create table if not exists admin (
id int(11) not null auto_increment,
nama varchar(20) not null,
no_telp varchar(20) null,
alamat varchar(50) null,
email varchar(50) null,
primary key (id)
);
You give no congret error message. I think it's not an error of if exists but maybe of the primary key.
Look at MySQL reference.
Try:
create schema if not exists appkasir;
use appkasir;
create table if not exists admin (
id int(11) not null auto_increment primary key,
nama varchar(20) not null,
no_telp varchar(20) null,
alamat varchar(50) null,
email varchar(50) null
);
I am working on creating table in to my database with mysql and here is my code:
mysqli_query($link, "CREATE TABLE IF NOT EXISTS `review` (
`clients_id` int(15) NOT NULL AUTO_INCREMENT,
`client_id` varchar(150) NOT NULL DEFAULT '',
`rating` tinyint(2) NOT NULL DEFAULT '0',
`proj_date` date NOT NULL DEFAULT '0000-00-00',
`proj_desc` text NOT NULL DEFAULT '',
`photoname` text NOT NULL,
`companyname` text NOT NULL,
`feedback` text NOT NULL,
`status` tinyint(1) NOT NULL DEFAULT '0',
`emailid` varchar(100) NOT NULL DEFAULT '',
`customratings` varchar(100) NOT NULL DEFAULT '',
`photo_option` varchar(100) NOT NULL DEFAULT '',
`title` varchar(100) NOT NULL DEFAULT '',
`citation` varchar(100) NOT NULL DEFAULT '',
`date_option` varchar(100) NOT NULL DEFAULT '',
`rating_option` varchar(100) NOT NULL DEFAULT '',
PRIMARY KEY (`clients_id`),
FULLTEXT KEY `feedback` (`feedback`)
) ENGINE=MyISAM AUTO_INCREMENT=1") or mysqli_error($link);
But this is not reflecting into my database ? Why were I may be going wrong ?
but I tried creating other table with the following code
mysqli_query($link, "CREATE TABLE IF NOT EXISTS `setting` (
`id` int(11) NOT NULL auto_increment,
`script_url` text NOT NULL,
`date` varchar(4) NOT NULL,
`rateing` varchar(4) NOT NULL,
`photo` varchar(4) NOT NULL,
`dateformat` varchar(4) NOT NULL,
`page_limit` int(4) NOT NULL,
`proj_desc` varchar(4) NOT NULL,
`companyname` varchar(4) NOT NULL,
`text_color` varchar(255) NOT NULL,
`citation_color` varchar(255) NOT NULL,
`bg_color` varchar(255) NOT NULL,
`border_color` varchar(255) NOT NULL,
`ratingsformat` varchar(250) NOT NULL,
`rating` varchar(250) NOT NULL,
`customratings` varchar(250) NOT NULL,
`speed` varchar(250) NOT NULL,
`pagination` varchar(250) NOT NULL,
`version` varchar(250) NOT NULL,
`global_option` varchar(250) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=0;
") or mysqli_error($link);
it is being created correctly and both the tables are in the same file
No you cannot create table using an insert statement.
There are four types of SQL statements:
DML (DATA MANIPULATION LANGUAGE)
DDL (DATA DEFINITION LANGUAGE)
DCL (DATA CONTROL LANGUAGE)
TCL (TRANSACTION CONTROL LANGUAGE)
DML is your SELECT, INSERT, UPDATE and DELETE statements...
DDL is you your CREATE, ALTER and DROP statements.
See more info about types of SQL statements
In order to insert data in your table, first you need to create it.
How to create sql table from php
No. "INSERT INTO" used to insert the data to existing table only.You should create the table with respective column before try to insert the values.
Or you can check the table exist or not before going insert."If exists" u can insert the value else just create and insert the values.
This worked for me but I don't know how?
I just removed DEFAULT '' present while creating review table and table just got created
Here is edited code
mysqli_query($link, "CREATE TABLE IF NOT EXISTS `review` (
`clients_id` int(15) NOT NULL AUTO_INCREMENT,
`client_id` varchar(150) NOT NULL,
`rating` tinyint(2) NOT NULL,
`proj_date` date NOT NULL,
`proj_desc` text NOT NULL,
`photoname` text NOT NULL,
`companyname` text NOT NULL,
`feedback` text NOT NULL,
`status` tinyint(1) NOT NULL,
`emailid` varchar(100) NOT NULL,
`customratings` varchar(100) NOT NULL,
`photo_option` varchar(100) NOT NULL,
`title` varchar(100) NOT NULL,
`citation` varchar(100) NOT NULL,
`date_option` varchar(100) NOT NULL,
`rating_option` varchar(100) NOT NULL,
PRIMARY KEY (`clients_id`),
FULLTEXT KEY `feedback` (`feedback`)
) ENGINE=MyISAM AUTO_INCREMENT=1") or mysqli_error($link);
When I run the following query
$sql ="SELECT * FROM user_info JOIN Notifications ON user_info.user_info_id =Notifications.Sender_id AND Notifications.STATE=0 LIMIT 1";
$query=mysqli_query($con,$sql);
$num_rows=mysqli_num_rows($query);
$message=''
if($num_rows > 0){
$con=mysqli_fetch_assoc($query);
switch ($con['Notification_Type']){
case'events':
$var="Notifications".$con['user_info_id'];
$sql_shown="SELECT *FROMevent WHERE event.notification_shown = 0 AND event.user_info_id='$var'LIMIT 1";
$query_vi=mysqli_query($con,$sql_shown);
$num_rows_vi=mysqli_num_rows($query_vi);
$message.=$con['Sender_id']."has created a Event";
echo $message;
break;
}
}
I get the following error:
mysqli_query() expects parameter 1 to be mysqli, array given in
This is my user table:
CREATE TABLE IF NOT EXISTS user_info(
user_info_id INT(11) NOT NULL AUTO_INCREMENT,
u_first_name VARCHAR(255) NOT NULL,
u_last_name VARCHAR(255) NOT NULL,
u_email VARCHAR(255) NOT NULL,
u_mobile VARCHAR(255) NOT NULL,
role ENUM('1yearM','1yearN','1yearR','1yearU','1yearS','2M','2R','2N','2U','2S','3M','3R','3N','3U','3S','4M','4R','4N','4U','4S','professor','librarian','admission_department') NOT NULL,
password VARCHAR(255) NOT NULL,
u_ip VARCHAR(255) NOT NULL,
signup_date DATETIME NOT NULL,
last_login DATETIME NOT NULL,
act_code VARCHAR(255) NOT NULL,
activation enum('1','0') NOT NULL DEFAULT '0',
PRIMARY KEY (user_info_id),
UNIQUE KEY (u_email,u_mobile)
)
This is my event table:
CREATE TABLE IF NOT EXISTS Event(
Event_id INT(11) NOT NULL AUTO_INCREMENT,
Event_Name VARCHAR(255) NOT NULL,
Event_location VARCHAR(255) NOT NULL,
Event_Organizer VARCHAR(255) NOT NULL,
Event_Date_Posted DATETIME NOT NULL,
Event_Starting_timings DATETIME NOT NULL,
Event_Ending_timings DATETIME NOT NULL,
Event_Day VARCHAR(255) NOT NULL,
Event_Description text NOT NULL,
Event_file_name VARCHAR(255) NOT NULL,
Event_file_path VARCHAR(255) NOT NULL,
Event_file_size VARCHAR(255) NOT NULL,
user_info_id INT(11) NOT NULL,
notification_shown ENUM('1','0') NOT NULL DEFAULT '0',
PRIMARY KEY (Event_id),
FOREIGN KEY (user_info_id) REFERENCES user_info(user_info_id)
)
This is my notification table:
CREATE TABLE IF NOT EXISTS Notifications(
Notifications_id INT(11) NOT NULL AUTO_INCREMENT,
Notification_Type VARCHAR(255) NOT NULL,
Notification_Content VARCHAR(255) NOT NULL,
Notification_Created_Date DATETIME NOT NULL,
Notification_State ENUM('read','unread') NOT NULL DEFAULT 'unread',
Is_Notification_Delete ENUM('1','0') NOT NULL DEFAULT '0',
Notification_Deleted_Date DATETIME NOT NULL,
Sender_id INT(11) NOT NULL,
STATE ENUM('1','0') NOT NULL DEFAULT '0',
Recipient_id INT(11) NOT NULL,
PRIMARY KEY (Notifications_id)
)
You overwrite your $con variable with this line:
$con=mysqli_fetch_assoc($query);
Before that line your $con variable was a valid MySQLi connection handle. After that line it is not an array. Therefore your mysqli_query() call complain that the first argument isn't a mysqli connection/object/handle anymore, but instead is now an array (which it shouldn't).
Change your $con=mysqli_fetch_assoc($query); so it doesn't overwrite your $con variable with the MySQLi connection/object/handle, but instead write the result in a different variable (maybe $userinfo?).
Check if your $con it's been created with properly method mysqli_connect('').
I want to create some table through PHP but it fails everytime, but the same code excutes perfectly when excuted through MYsql console or PHPMyAdmin
The SQLs are
$sql = <<<SQL_CODE
CREATE TABLE IF NOT EXISTS `bid` (
`aid` int(11) unsigned NOT NULL,
`uid` int(11) unsigned NOT NULL,
`name` varchar(20) NOT NULL,
`amount` smallint(6) unsigned NOT NULL,
`time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS `item` (
`aid` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(40) NOT NULL,
`description` varchar(120) NOT NULL,
`img` int(11) unsigned NOT NULL,
`amount` smallint(6) unsigned NOT NULL,
`strtdate` date NOT NULL,
`enddate` date NOT NULL,
`uid` int(11) unsigned NOT NULL,
`uname` varchar(20) NOT NULL,
`uamount` int(11) unsigned NOT NULL,
PRIMARY KEY (`aid`)
);
CREATE TABLE IF NOT EXISTS `user` (
`uid` int(11) unsigned NOT NULL AUTO_INCREMENT,
`email` varchar(40) NOT NULL,
`password` varchar(40) NOT NULL,
`nameF` varchar(20) NOT NULL,
`nameL` varchar(20) NOT NULL,
`sex` varchar(1) NOT NULL,
`img` int(11) unsigned NOT NULL,
`country` varchar(10) NOT NULL,
`state` varchar(20) NOT NULL,
`address` varchar(120) NOT NULL,
`code` varchar(8) NOT NULL,
`isAdmin` varchar(1) NOT NULL,
PRIMARY KEY (`uid`),
UNIQUE KEY `email` (`email`)
);
SQL_CODE;
$sql2 = 'CREATE DATABASE `'.$db.'`;';
$sql3 = 'USE `'.$db.'`; ';
$sql4 = 'drop Database `'.$db.'``;';
if (!mysql_query($sql2)) echo mysql_error();
if (!mysql_query($sql3)) echo mysql_error();
//sleep(1);
if (!mysql_query($sql)) echo mysql_error();
echo $sql2.' '.$sql3.' '.$sql;
Error I'm getting
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 item ( aid int(11) unsigned NOT NULL AUTO_INCREMENT,' at line 1CREATE DATABASE auction; USE auction; CREATE TABLE IF NOT EXISTS bid ( aid int(11) unsigned NOT NULL, uid int(11) unsigned NOT NULL, name varchar(20) NOT NULL, amount smallint(6) unsigned NOT NULL, time timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP); CREATE TABLE IF NOT EXISTS item ( aid int(11) unsigned NOT NULL AUTO_INCREMENT, name varchar(40) NOT NULL, description varchar(120) NOT NULL, img int(11) unsigned NOT NULL, amount smallint(6) unsigned NOT NULL, strtdate date NOT NULL, enddate date NOT NULL, uid int(11) unsigned NOT NULL, uname varchar(20) NOT NULL, uamount int(11) unsigned NOT NULL, PRIMARY KEY (aid));CREATE TABLE IF NOT EXISTS user ( uid int(11) unsigned NOT NULL AUTO_INCREMENT, email varchar(40) NOT NULL, password varchar(40) NOT NULL, nameF varchar(20) NOT NULL, nameL varchar(20) NOT NULL, sex varchar(1) NOT NULL, img int(11) unsigned NOT NULL, country varchar(10) NOT NULL, state varchar(20) NOT NULL, address varchar(120) NOT NULL, code varchar(8) NOT NULL, isAdmin varchar(1) NOT NULL, PRIMARY KEY (uid), UNIQUE KEY email (email));
From the mysql_query manual;
mysql_query() sends a unique query (multiple queries are not
supported)...
You need to split your triple CREATE TABLE statement into 3 separate statements and it will work.
I think that is a problem with multiple queries. I think that is solution.
http://php.net/manual/en/function.mysql-query.php
*mysql_query() sends a unique query (multiple queries are not supported) to the currently active database on the server that's associated with the specified link_identifier*
Just split them up and it will work.
I just moved to mysqli and I was wondering: can I do a multiple query with the prepared statements?
Here is the example: I need to check if this username is also in the table "future_user" and not just in "user" as it is doing right now. For code appeal I'd rather not write again the same function just changing "user" with "future_user".
function isFreeUsername($string)
{
$DB = databaseConnect();
$stmt = $DB->prepare("SELECT * FROM user WHERE username=? LIMIT 1");
$stmt->bind_param("s", $username);
if(isset($_SESSION) && isset($_GET['username'])) $username = $_GET['username'];
else $username = $string;
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows > 0) $return = 0;
else $return = 1;
$stmt->close();
$DB->close();
return $return;
}
TABLES:
CREATE TABLE user
(
uid mediumint(6) unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY,
username varchar(15) NOT NULL,
password varchar(15) BINARY NOT NULL,
mail varchar(50) NOT NULL,
name varchar(50) NOT NULL,
surname varchar(50) NOT NULL,
birth char(10) NOT NULL,
sex tinyint(1) unsigned NOT NULL default 1,
address varchar(50) NOT NULL,
city varchar(50) NOT NULL,
zip char(5) NOT NULL,
province varchar(50) NOT NULL,
country tinyint(3) NOT NULL,
number1 varchar(50) NOT NULL,
number2 varchar(50) NOT NULL,
last_login TIMESTAMP,
registered TIMESTAMP,
online tinyint(1) unsigned default 0,
admin tinyint(1) unsigned default 0,
comment_allowed tinyint(1) unsigned default 0,
post_allowed tinyint(1) unsigned default 0
) ENGINE=InnoDB;
CREATE TABLE future_user
(
username varchar(15) NOT NULL,
password varchar(15) BINARY NOT NULL,
mail varchar(50) NOT NULL,
name varchar(50) NOT NULL,
surname varchar(50) NOT NULL,
birth char(8) NOT NULL,
sex tinyint(1) unsigned NOT NULL,
address varchar(50) NOT NULL,
city varchar(50) NOT NULL,
zip char(10) NOT NULL,
province varchar(50) NOT NULL,
country varchar(50) NOT NULL,
number1 varchar(50) NOT NULL,
number2 varchar(50) NOT NULL,
code char(10) NOT NULL
) ENGINE=InnoDB;
"SELECT *
FROM user u
LEFT JOIN future_user fu on fu.id = u.id
WHERE u.username=?
LIMIT 1"
With out seeing more of your table structure this what i can come up with.
This will select the user in future user too
You could do a CROSS JOIN to connect the two tables and query them that way
SELECT * FROM user JOIN future_user
WHERE user.username = ? OR future_user.username = ?
You'll probably need to tweak that * so that identically named columns in the two tables don't overlay each other.