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.
Related
I have it set up to echo when my tables create but the users table just won't, I've looked at multiple solutions but none of them has helped here my code
<?
phpinclude_once("index.php");
$tbl_users = "CREATE TABLE IF NOT EXISTS users
(
id INT(11) NOT NULL AUTO_INCREMENT,
username VARCHAR(16) NOT NULL,
email VARCHAR(64) NOT NULL,
password VARCHAR(64) NOT NULL,
gender ENUM('m','f') NOT NULL,
website VARCHAR(64) NULL,
country VARCHAR(64) NULL,
userlevel ENUM('a','b','c','d') NOT NULL DEFAULT a,
avatar VARCHAR(64) NULL,
ip VARCHAR(64) NOT NULL,
signup DATETIME NOT NULL,
lastlogin DATETIME NOT NULL,
notescheck DATETIME NOT NULL,
activated ENUM('0','1') NOT NULL DEFAULT 0,
PRIMARY KEY (id)),
UNIQUE KEY username (username,email))";
$query = mysqli_query($db_spooky, $tbl_users);
if ($query === TRUE)
{
echo "<h3>user table created OK :) </h3>";
}
else
{
echo "<h3>user table NOT created :( </h3>";
}
?>
CREATE TABLE IF NOT EXISTS users (id INT(11) NOT NULL AUTO_INCREMENT
,username VARCHAR(16) NOT NULL
,email VARCHAR(64) NOT NULL,password VARCHAR(64) NOT NULL
,gender ENUM('m','f') NOT NULL
,website VARCHAR(64) NULL
,country VARCHAR(64) NULL
,userlevel ENUM('a','b','c','d') NOT NULL DEFAULT 'a'
,avatar VARCHAR(64) NULL
,ip VARCHAR(64) NOT NULL
,signup DATETIME NOT NULL
,lastlogin DATETIME NOT NULL
,notescheck DATETIME NOT NULL,activated ENUM('0','1') NOT NULL DEFAULT 0
,PRIMARY KEY (id)
,UNIQUE KEY username (username,email))
Learn to organize your code instead of writing it in one long line for one, and two, ENUM default for a needs to be in single quotes and you had an extra closing bracket. The code above is the corrected version.
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 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>";
}
}
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.
Here is my USER table
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(100) NOT NULL,
`expiry` varchar(6) NOT NULL,
`contact_id` int(11) NOT NULL,
`email` varchar(255) NOT NULL,
`password` varchar(100) NOT NULL,
`level` int(3) NOT NULL,
`active` tinyint(4) NOT NULL DEFAULT '1',
PRIMARY KEY (`id`,`email`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
And here is my contact_info table
CREATE TABLE IF NOT EXISTS `contact_info` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`email_address` varchar(255) NOT NULL,
`company_name` varchar(255) NOT NULL,
`license_number` varchar(255) NOT NULL,
`phone` varchar(30) NOT NULL,
`fax` varchar(30) NOT NULL,
`mobile` varchar(30) NOT NULL,
`category` varchar(100) NOT NULL,
`country` varchar(20) NOT NULL,
`state` varchar(20) NOT NULL,
`city` varchar(100) NOT NULL,
`postcode` varchar(50) NOT NULL,
PRIMARY KEY (`id`,`email_address`),
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
The system uses username to login users. I want to modify it in such a way that it uses email for login. But there is no email_address in users table.
I have added foreign key - email in user table(which is email_address in contact_info).
How should I query database?
No, no, no, no no. Seriously, no. Don't make me come over there :-)
You're breaking third normal form by storing the email address twice.
The relationship need only be a short one, that of id. Assuming you're not guaranteeing the IDs will be identical in the two tables (i.e., my users.id isn't necessarily equal to my contact_info.id), just add a ci_id to the users table to act as a foreign key to the contact_info table.
Then the query to get a user's username and email will be something like:
select u.username, ci.email
from users u, contact_info ci
where u.username = 'paxdiablo'
and u.ci_id = ci.id;