I'm trying to create a table if it does not already exist in my database. For this I'm running this test which is working as intended:
$conn = mysql_connect("localhost", "twa222", "twa222bg");
mysql_select_db("airline222", $conn) or die ("Database not found " . mysql_error() );
$val = mysql_query("SELECT 1 from '$FLIGHTID'");
However my problem comes when I try to create the table itself, which is giving me the following error:
Problem with query: 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 ''passenger' SMALLINT NOT NULL, 'booking' CHAR(6), 'seat' VARCHAR(3))' at line 2
This is the code that is attempting to generate the table
if(!$val)
{
$sql = "CREATE TABLE ".$FLIGHTID." (
passenger SMALLINT NOT NULL PRIMARY KEY,
booking CHAR(6), seat VARCHAR(3) )";
$rs = mysql_query($sql) or die ("Problem with query" . mysql_error());
}
mysql_close($conn);
I originally thought it was the ".$FLIGHTID." that was causing the problem but when I changed that to simply be ABC I still got the same error.
Can anyone see where I am going wrong?
EDIT:
My SQL output when using ABC is:
CREATE TABLE ABC ( passenger SMALLINT NOT NULL PRIMARY KEY, booking CHAR(6), seat VARCHAR(3) )
Without using ABC it is:
CREATE TABLE ( passenger SMALLINT NOT NULL PRIMARY KEY, booking CHAR(6), seat VARCHAR(3) )
You use single quotes arround column names what is not allowed. Single qoutes indicates that the value inside is a litaral:
Change:
$val = mysql_query("SELECT 1 from '$FLIGHTID'");
to:
$val = mysql_query("SELECT 1 from $FLIGHTID");
Use mysqli_*or PDOinstead of deprecated mysql_* API.
Related
I am trying to make an SQL query that :
IF the $post_id exists then it updates the records,
IF NOT then then it creates the record
Here is my code
$vote_new_total = $vote_total + $vote;
$vote_count = $vote_count + 1;
$query = " INSERT INTO cute_review_vote (vote_total, vote_count)
VALUES ('$vote_new_total', '$vote_count')
ON DUPLICATE KEY UPDATE vote_total = $vote_new_total, vote_count = $vote_count
WHERE post_id = $post_id";
mysql_query($query) or trigger_error(mysql_error()." in ".$sql);
However, I keep getting the following error:
Notice: 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 'WHERE post_id = 214748364' at line 4 in in C:\xampp\htdocs\xbm-vote\do_vote.php on line 68
Is this an issue with my syntax or am I missing something more obvious than that?
Any help/advice would be greatly appreciated. Thanks.
There is no where with ON DUPLICATE statement. Always check syntax: http://dev.mysql.com/doc/refman/5.6/en/insert-on-duplicate.html
Also, that is not a secure query. Turn that into a prepared statement.
http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
EDIT: Updating answer since OP didn't understand usage of ON DUPLICATE statement:
ON DUPLICATE will consider that you're trying to insert a KEY value.
Consider the example table:
CREATE TABLE `user` (
`email` varchar(50) NOT NULL,
`name` varchar(20) NOT NULL,
`is_active` tinyint(4) NOT NULL,
`datecreated` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`email`)
);
And the query:
INSERT INTO user (email, name, is_active) VALUES ("user#user.com", "User", 1)
ON DUPLICATE KEY UPDATE name = "User Edited", is_active = 0
Since we're setting PRIMARY KEY as email, and the insert statement is inserting a key, then, at the second time you run the query, ON DUPLICATE would run once a email is already on the table, because it is the KEY and you are trying to insert it again, but you defined a ON DUPLICATE KEY ....
If a table runs with a AUTO_INCREMENT column, is most likely you have to SELECT post_id applying some filter with WHERE statement.
Ok, I found my problem.
INSERT INTO cute_review_vote (post_id, vote_total, vote_count)
VALUES ('$post_id', '$vote_new_total', '$vote_count')
ON DUPLICATE KEY UPDATE vote_total = $vote_new_total, vote_count = $vote_count
I realized, thanks to Fabiano, that the WHERE clause is not required.
WHERE post_id = $post_id"
Is simply replaced by defining the database entry within the INSERT INTO command.
when I run this php file in my wamp server it connects to database, selects database but not create table .
the output is this:
connected to database succussfully.
connected to database store_db succussfully.
table users was not created.
what is the problem???
php code:
<?php
$sql='CREATE TABLE users
(
PID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(PID),
NAME CHAR(20),
PASSWORD CHAR(15),
)';
mysql_connect("localhost","root","") or die('could not connect to database.');
echo 'connected to database succussfully.<br>';
mysql_select_db('store_db') or die('database store_db not found.');
echo 'connected to database store_db succussfully.<br>';
mysql_query($sql) or die('table users was not created');
echo 'table users was created in database store_db succussfully.<br>';
?>
<?php
$sql='CREATE TABLE users
(
PID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(PID),
NAME CHAR(20),
PASSWORD CHAR(15),
)';
remove the comma after PASSWORD CHAR(15),
in the event of an error, you can always retrieve errors using mysql_error().
however. you should not be using the old mysql functions. much better and more secure options exist in the PDO and MySQLi extensions.
Your $sql:
$sql='CREATE TABLE users
(
PID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(PID),
NAME CHAR(20),
PASSWORD CHAR(15),
)';
should be:
$sql='CREATE TABLE users
(
PID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(PID),
NAME CHAR(20),
PASSWORD CHAR(15)
)';
You should remove comma right after PASSWORD CHAR(15)
To get the proper error message always use below code so that you can figure out exact error in future.
mysql_query($sql) or die(mysql_error());
Make sure the MySQL user you are attempting to create the table with has permissions to do so. (e.g. the user has been granted the 'CREATE' privileges for that database.)
i want to create a table in the database using php (mysql_querry)
Table is having 'n' number of attributes.
out of n, n-2 attribute names are available in the array.
I can't explain where i am getting the array but it looks like this-
http://i.stack.imgur.com/tH98f.png
Here is the code for generating String to execute in mysql_querry.
$str="CREATE TABLE $register_name(id int NOT NULL AUTO_INCREMENT, date DATE, ";
$j=0;
while($j<$i)
{
$str=$str.$roll_no[$j]." int(100), ";
$j++;
}
$str=$str."PRIMARY KEY(id))";
require('blogic.php');
$obj = new blogic();
$createtable=$obj->create($str);
When i echo the $str, I get this:
CREATE TABLE $register_name(id int NOT NULL AUTO_INCREMENT, date DATE, 913310128 int(100), 0913310129 int(100), PRIMARY KEY(id))
However, it is giving error like this
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 '913310128 int(100), 0913310129 int(100), PRIMARY KEY(id))' at
line 1
I don't understand the problem. when i don't use roll_no array, it works fine..
Please let me know what is the problem in this.
From the docs:
"Identifiers may begin with a digit but unless quoted may not consist solely of digits."
So, you could just quote the name:
$str=$str."`".$roll_no[$j]."` int(100), ";
Or, prefix it with a letter:
$str=$str."c".$roll_no[$j]." int(100), ";
I'm trying to create a table whose name is the value of what is stored inside the variable $name. I have tried numerous different methods but none seem to work for me. Here is the code I am using currently:
mysql_connect("localhost", "peltdyou_admin", "123456") or die(mysql_error());
mysql_select_db("peltdyou_orders") or die(mysql_error());
mysql_query("CREATE TABLE '" .$_POST['name']. "' ( name VARCHAR(30), age INT, car VARCHAR(30))");
I know it is something to do with '" .$_POST['name']. "' but I can't work out what.
I have tried '$name' in its place which gets it's value from further up in the code.
Any help would be great!
Use backticks around table name, not quotes. And escape the input! Also, while this works on localhost, make sure that the user running on your production server has the privilege to CREATE tables (usually it's not, AFAIK, on shared hostings of course).
A word of warning: are you really sure you want to create a table on a user input?? how many tables are you going to create in this way? Can't you just redesign the whole thing so that you insert values instead?
$name = mysql_real_escape_string($_POST['name']);
mysql_query("CREATE TABLE `".$name."` ( name VARCHAR(30), age INT, car VARCHAR(30))");
Put it in another variable and it will work, there's a conflict with the "'" character in the POST variable and in the mysql_query.
<?php
mysql_connect("localhost", "peltdyou_admin", "123456") or die(mysql_error());
mysql_select_db("peltdyou_orders") or die(mysql_error());
$name = mysql_real_escape_string($_POST['name']);
mysql_query("CREATE TABLE '$name' ( name VARCHAR(30), age INT, car VARCHAR(30))");
?>
I posted this code to help you in your code but you should not use the mysql_* functions you should use the mysqli_* functions.
You can read more about them here:
http://php.net/manual/en/book.mysqli.php
You should really be using PDO or MySQLi instead of mysql_* functions. mysql_* functions are in the process of being deprecated and they are full of security holes.
With that said you don't need to quote your table name and instead should use nothing or backticks.
Using the newest Mysqli connector, you can do something like this:
1. Create a variable from the user's input like so $variable=$_POST['name']
2. Use the variable in your query as shown in the complete code below here
$variable=$_POST['name'];
mysqli_connect("localhost", "peltdyou_admin", "123456") or die(mysql_error());
mysqli_select_db("peltdyou_orders") or die(mysqli_connect_error());
mysqli_query("CREATE TABLE $variable ( name VARCHAR(30), age INT, car VARCHAR(30))");
$query = "CREATE TABLE $name" . '(
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
age INT,
name varchar(30),
car VARCHAR(30)
)';
CREATE TABLE IF NOT EXISTS `products` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(128) NOT NULL,
`description` text NOT NULL,
`price` double NOT NULL,
`created` datetime NOT NULL,
`modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;
I have an Auto increment ID column in my table and it does work fine when I insert the records using PHP. I have to delete the records from this table every hour using the DELETE statement. I changed the PHP.ini file and restarted the machine. For some reason Auto increment ID started from '1' again. There were no records in the table when I restarted the machine. I am using PHP 5.3.8 and MySQL 5.5.21 running under IIS. Please let me know if there are any suggestions. Here is my table schema.
CREATE TABLE `test_table` (
`test_id` int(11) NOT NULL AUTO_INCREMENT,
`test_date` datetime DEFAULT NULL,
`test_location` varchar(2000) NOT NULL,
`test_summary` varchar(4000) NOT NULL,
`create_dtm` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`test_id`)
) ENGINE=InnoDB
Here is my insert query
$Sql = "INSERT INTO test_table(test_date, test_location, test_summary) VALUES ('" .sDate. "', '" .$location. "', '" .$summary. "')";
$Result = mysql_query($Sql) or die(mysql_error());
$new_id = MySql_Insert_Id();
Here is DELETE.
$Sql1 = "DELETE FROM test_table";
$Result1 = mysql_query($Sql1) or die(mysql_error());
Using a DELETE with no where clause is the same as TRUNCATING a table, hence they both reset the Next AutoIndex value for the table. (Which is what people would normally want / expect)
Could use something like the following to get around this in your case maybe:
mysql_query(
sprintf(
"ALTER TABLE tbl_name AUTO_INCREMENT = %d",
mysql_insert_id() + 1
) );
(If the DELETE clears the insert value then you will just need to cache it before your DELETE / TRUNCATE)