create and insert in a single query - php

<?php
mysql_query("CREATE TABLE IF NOT EXISTS test.$p (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL DEFAULT '',
`colum` varchar(255) NOT NULL DEFAULT '',
`ord` varchar(255) NOT NULL DEFAULT '',
`tex` varchar(255) NOT NULL DEFAULT '',
`search` varchar(255) NOT NULL DEFAULT '',
`count` varchar(255) NOT NULL DEFAULT '',
`order` varchar(255) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
)ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;
INSERT INTO $p ( `title`, `colum`, `ord`, `tex`, `search`, `count`, `order`) VALUES
('$a', '$b', '$c', '$d', '$f', '$h', '$g'); ");
?>
I am working in a PHP language . $r is my database and $p is my table name
In this I am creating a table , if table is not created and if the table is created then i want to insert the values in the respective column given above but I am not good at mysql_query so I don't know where to add the insert query
I found a solution for my problem but this code is properly working in the phpmyadmin but when i run this code using php , it show me nothing inthe database

You can not execute two queries with a single mysql_query().
Make another call to mysql_query() with the INSERT query as the parameter.
If you absolutely must execute multiple queries in a single function call, change your mysql engne to mysqli, then use mysqli_multi_query() like so:
mysqli_multi_query ($link, 'query1;query2;query3;...');
Please keep in mind that although both approaches issue queries sequentially, their execution is not atomic. If you need atomicity, use a TRANSACTION.

The 13.1.17. CREATE TABLE Syntax can do something like:
CREATE TABLE IF NOT EXISTS `table1` (
`col1` INT (11) DEFAULT NULL,
`col2` INT (11) DEFAULT NULL
)
SELECT 1 `col1`, 2 `col2`;
and should work with mysql_query

Related

error on local mysql but not on RDS mysql

I have a mysql insert query which runs on aws RDS(Live env) but throws an error on my local(local env).
on local I'am using mysql V-5.6
$sql = "INSERT INTO `users` (`id`,
`name`,
`email`,
`pass`)
values('','omi','omi#gmail.com','123123')
id is not null and auto_increment.
The error which i get on local is 'Incorrect integer value: '' for column 'id' at row 1'
but when this executed on live env all the data gets inserted into table.
I cant understand what exactly is happening here. please help. thank you.
DDL of users table.
local
CREATE TABLE `users`
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(256) DEFAULT '',
`email` varchar(256) NOT NULL,
`pass` varchar(256) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=25986 DEFAULT CHARSET=utf8;
Live
CREATE TABLE `users` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(254) DEFAULT '',
`email` varchar(256) NOT NULL,
`pass` varchar(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=26046 DEFAULT CHARSET=utf8;
I believe the error is with those quotes (''). When you want to do an insert with an auto_increment field, you have to use null as argument in the auto_increment field position.
See if this works:
$sql = "INSERT INTO `users`
(`id`, `name`, `email`, `pass`)
values(null,'omi','omi#gmail.com','123123');
EDIT 1
Using null doesn't generate any error because internally the DBMS is prepared to receive such an argument. It understands that is its duty to generate the next number of the sequence and if it hasn't any, 0 (of type integer in your case) is inserted first. I know defining "not null" in the DDL of a field and then using "null" in the DML insert statement for that exact field may look confusing, but it's just the right way to use the auto_increment feature.
From the documentation:
If the column is declared NOT NULL, it is also possible to assign NULL to the column to generate sequence numbers.
Also, if using an empty string as argument in an statement doesn't generate any error, it could maybe be because RDS interface has an internal function that converts empty to null. Something like the nullif function in MySQL.
You can't do it like that. Either dont even mention 'id' or give it null value.
$sql = "INSERT INTO `users` (
`name`,
`email`,
`pass`)
values('omi','omi#gmail.com','123123')
OR:
$sql = "INSERT INTO `users` (`id`,
`name`,
`email`,
`pass`)
values('NULL','omi','omi#gmail.com','123123')

PHP SQL query slow?

Here is my function which i am using to un-follow users.It first DELETE the relationship between users and all the notifications that are related to this relationship.Then it INSERT a new notification for user which we are going to un-follow and then UPDATE his followers count (as one follower has left).I am using multi_query and this query seems to be bit slower on large database and i want to know whether it's a good practice or not or is there is any more complex form of query to get the job done.
PHP Function
// 'By' is the array that hold logged user and 'followed' is the user id which we are going to unfollow
function unFollowUser($followed,$by) {
$following = $this->getUserByID($followed);// Return fetch_assoc of user row
if(!empty($following['idu'])) { // if user exists
// return user followers as number of rows
$followers = $this->db->real_escape_string($this->numberFollowers($following['idu'])) - 1;
$followed_esc = $this->db->real_escape_string($following['idu']);
$by_user_esc = $this->db->real_escape_string($by['idu']);
// delete relationship
$query = "DELETE FROM `relationships` WHERE `relationships`.`user2` = '$followed_esc' AND `relationships`.`user1` = '$by_user_esc' ;" ;
// delete notification (user started following you )
$query.= "DELETE FROM `notifications` WHERE `notifications`.`not_from` = '$by_user_esc' AND `notifications`.`not_to` = '$followed_esc' ;" ;
// Insert a new notification( user has unfollowed you)
$query.= "INSERT INTO `notifications`(`id`, `not_from`, `not_to`, `not_content_id`,`not_content`,`not_type`,`not_read`, `not_time`) VALUES (NULL, '$by_user_esc', '$followed_esc', '0','0','5','0', CURRENT_TIMESTAMP) ;" ;
// update user followers (-1)
$query .= "UPDATE `users` SET `followers` = '$followers' WHERE `users`.`idu` = '$followed_esc' ;" ;
if($this->db->multi_query($query) === TRUE) {
return 1;
} else {
return 0;
}
} else {
return 0;
}
}
Table structures
--
-- Table structure for table `notifications`
--
CREATE TABLE IF NOT EXISTS `notifications` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`not_from` int(11) NOT NULL,
`not_to` int(11) NOT NULL,
`not_content_id` int(11) NOT NULL,
`not_content` int(11) NOT NULL,
`not_type` int(11) NOT NULL,
`not_read` int(11) NOT NULL,
`not_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Table structure for table `relationships`
--
CREATE TABLE IF NOT EXISTS `relationships` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user1` int(11) NOT NULL,
`user2` int(11) NOT NULL,
`status` int(11) NOT NULL,
`time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Table structure for table `users`
--
CREATE TABLE IF NOT EXISTS `users` (
`idu` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(32) NOT NULL,
`password` varchar(256) NOT NULL,
`email` varchar(256) NOT NULL,
`first_name` varchar(32) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`last_name` varchar(32) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`verified` int(11) NOT NULL,
`posts` text CHARACTER SET utf32 NOT NULL,
`photos` text CHARACTER SET utf32 NOT NULL,
`followers` text CHARACTER SET utf32 NOT NULL,
UNIQUE KEY `id` (`idu`),
UNIQUE KEY `idu` (`idu`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
In my testing, multi_query has been the fastest way to execute multiple different queries. Why do you feel it's running slow? Compared to what?
Anyway, improvements could come from adding indexes to some of the columns you search frequently:
relationships.users2
relationships.users1
notifications.not_from
notifications.not_to
users.idu
Adding indexes makes searching faster, but it has at least two downsides:
Makes the DB a lot more resource hungry, which could affect your server performance
Makes writing operations take longer
I don't see any problem with your current queries. Really consider whether the slow performance you're seeing comes from the DB queries themselves, or from the rest of your PHP process. Try measuring the script time with the queries, then skipping the queries and taking another measurement (you could hardcode query results). It will give you an idea of whether the slowness is attributable to something else.
Either way, benchmark.
Try creating index on user where deletes are running , this may speed up query

Update record in table if it exists (with clause) or creates it if not

I am attempting to write a query that will update the record if it exists, or create it if it does not, however I want to do that based on the condition that text_value is not already set.
I initally thought of using REPLACE, but that does not support a WHERE clause.
REPLACE INTO settings
SET var_name = '',
var_group = '',
text_value = '',
country_id = ''
Can I do what I want to do in one query? I am trying to do so without having to write something like this where I have two queries in my PHP:
SELECT FROM settings WHERE text_value != '' AND country_id = $country_id
IF that returns no results then
INSERT INTO settings...
This is my table DDL information:
CREATE TABLE `settings` (
`settings_id` int(11) NOT NULL auto_increment,
`var_name` varchar(50) default NULL,
`var_group` varchar(26) NOT NULL,
`text_value` text NOT NULL,
`country_id` int(11) NOT NULL,
PRIMARY KEY (`settings_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

mysql retrieve autoinc value for join insert

We have the following two tables:
CREATE TABLE IF NOT EXISTS `gp` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`amount` decimal(15,2) NOT NULL,
`user` varchar(100) NOT NULL DEFAULT '',
`status` tinyint(2) NOT NULL DEFAULT '1',
`ip` varchar(20) NOT NULL DEFAULT 'N/A',
`token` varchar(100) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;
CREATE TABLE IF NOT EXISTS `gp_logs` (
`id` int(11) NOT NULL,
`log` varchar(1000) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
We JOIN them, for statistics, but we do this rarely, since the data from the 2nd table is not used too often except when we need to verify things.
Considering that we have many queries per second, how can our query be optimized to use 1 INSERT query instead of two and to insert the correct id in the 2nd table (gp_logs) that was generated by the INSERT into table gp?
Right now, we do a combination of MYSQL with PHP:
mysqli_query($con,"INSERT INTO `gp` (amount,user) VALUES ('1234','1')");
$id = mysqli_insert_id($con);
mysqli_query($con,"INSERT INTO gp_logs(id,log) VALUES ('$id','some_data')");
We want to eliminate the requirement of PHP for getting the last inserted ID and to insert both entries by running a single INSERT query (with a JOIN).

values are not inserting

<?php
$ll=mysql_query("CREATE TABLE IF NOT EXISTS p (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL DEFAULT '',
`colum` varchar(255) NOT NULL DEFAULT '',
`ord` varchar(255) NOT NULL DEFAULT '',
`tex` varchar(255) NOT NULL DEFAULT '',
`search` varchar(255) NOT NULL DEFAULT '',
`count` varchar(255) NOT NULL DEFAULT '',
`order` varchar(255) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
)ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;INSERT INTO p (title,colum,ord,tex,search,count,order) VALUES ('$a','$b','$c','$d','$f','$h','$g');") or die(mysql_error()) ;
if($ll){
echo "insert AND CREATE ";}
else {echo "fail"; }
?>
I am working in a php language . In this page if the table is not created 1st create it and then insert the values into the column
After creating the table , I am inserting the values into the table but it showing me the error in the insert query
I am getting a this error- 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 p VALUES ('count','name','asc','1','search','count','order ')' at line 11
what am i doing wrong
I am not absolutly sure if that is the problem but you are passing 7 values in your INSERT statement while your table deffinition has 8 fields.
I assume you are doing that because 'id' field is autoincremental. However, if that is the case, you should specify which columns correspond with your values in the insert statement:
INSERT INTO $p (title, column, ord, ...) VALUES ('$a','$b','$c','$d','$f','$h','$g')
Here is a dry run seperating the two statements - should work:
<?php
$querys[]="CREATE TABLE IF NOT EXISTS $p (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL DEFAULT '',
`colum` varchar(255) NOT NULL DEFAULT '',
`ord` varchar(255) NOT NULL DEFAULT '',
`tex` varchar(255) NOT NULL DEFAULT '',
`search` varchar(255) NOT NULL DEFAULT '',
`count` varchar(255) NOT NULL DEFAULT '',
`order` varchar(255) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
)ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1";
$querys[]="INSERT INTO $p VALUES (null,'$a','{$b}','{$c}','{$d}','{$f}','{$h}','{$g}')";
foreach($querys as $sql) {
$ll = mysql_query($sql);
$error=mysql_error();
if($error!='') {
print $sql."\n";
die($error);
}
}
?>
INSERT INTO p (title,colum,ord,tex,search,count,order) VALUES ('$a','$b','$c','$d','$f','$h','$g')
should be
INSERT INTO p (`title`,`colum`,`ord`,`tex`,`search`,`count`,`order`) VALUES ('$a','$b','$c','$d','$f','$h','$g')
Hence order is a mysql keyword
you have ended the insert statement with a " double quote but not started you can write either
INSERT INTO p (title,colum,ord,tex,search,count,order) VALUES ('$a','$b','$c','$d','$f','$h','$g');
or you can write
("INSERT INTO p (title,colum,ord,tex,search,count,order) VALUES ('$a','$b','$c','$d','$f','$h','$g')");
try it in your code
note - please do not use mysqli and mysql in same code, rather you can use mysqli PDO

Categories