creating DB table by giving input from php text box - php

I want to make a table in a database, by giving the name of that table as an input from a text box.
<?php
$tablename = $_POST['tablename'];
// Create a MySQL table in the selected database
mysql_query("CREATE TABLE $tablename(
id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id),
firstpublish VARCHAR(255),
descriptions VARCHAR(255))") or die(mysql_error());
?>
it makes the table and the field, but i can't insert any data in it. When i run the code below
<?php
$firstpublish = $_POST['firstpublish'];
$descriptions = $_POST['descriptions'];
if(isset($_POST['firstpublish']) || ($_POST['descriptions']))
{
$order="INSERT INTO $tablename (id,firstpublish,descriptions) VALUES ('','$firstpublish','$descriptions')";
$result = mysql_query($order) or die (mysql_error());
}
?>
it showing an error message
"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 '( id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id), firstpublish VARCHA' at line 1"
how can i fixed this problem.
-thankyou.

My best guess would be that your first query is somehow being rerun with a blank value for $tablename
If this is a publicly accessible page, i'd be very careful about creating tables from user input. You also probably want to (at the very least) run $tablenale through mysql_real_escape_string() and change CREATE TABLE to CREATE TABLE IF NOT EXISTS

The error is here:
mysql_query("CREATE TABLE $tablename(
Since you are mixing a variable in a quoted string, you insert whitespace after its name, because "$tablename(" is illegal name and will most likely be replaced will null, so the SQL-statement will actually be seen for MySQL as
CREATE TABLE id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id), firstpublish VARCHAR(255), descriptions VARCHAR (255))
which, in turn, is a syntax error.
Solution: Add a space between $tablename and "(".

Related

LIKE % XX(YY)GG % not working in MySQL

I have used Stored procedure to check whether a name exist in a table or not by using the following code snippet..
BEGIN
IF ids = 0 THEN
SELECT * FROM table_name WHERE `table_id` = alb_id AND name LIKE CONCAT('%',var_name,'%');
END IF;
END
I got the solution if the name doesn't contain any special characters or brackets, like XXXX.
If the name contains any brackets means result not came, like XX(YY)GG.
Suggest me for the best solution
Edited:
In this if a name exist already i should not insert it again, for this condition i used this procedure. If it returns mysql_num_rows > 0 means i wont insert, else i will insert the name into my table..
My sample names are,..
Turning Tables (Live Acoustic)
Hiding My Heart
Someone Like You (Live Acoustic)
Right Now (Na Na Na)
Keep You Much Longer
Someone Like You
In the list of name "Someone Like You" and "Someone Like You (Live Acoustic)" are two different names, i want to identify the name "Someone Like You (Live Acoustic)" is already exist or not..
How do i do?
CREATE TABLE `stack_test` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`text` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB CHARSET=utf8;
INSERT INTO `blur_new`.`stack_test` (`id`, `text`) VALUES ('1', 'run (rabbit) run');
INSERT INTO `blur_new`.`stack_test` (`id`, `text`) VALUES ('2', 'test');
set #a = 'n (rabbit)';
select * from stack_test where text like concat('%',#a,'%');
results in:
1 |run (rabbit) run
So, it works.
check the rest of the conditions in where clause
check how are you passing the value
you might gonna have to check you data types. I have a feeling something is not right there

update cell value if value not already in

I have to update the column File on the TABLE TEST. This column contains the files related to the row. Each file is separated by a |.
An example could be
ID NAME FILE
1 apple fruit.png | lemon.png
Now when I add a new file to the FILE column I use this query:
$link->query("UPDATE TEST SET File = CONCAT(File, '$dbfilename') WHERE id = '$p_id'")
where $dbfilename can be e.g. pineapple.jpg |
The problem is that, if $dbfilename is already on the File values, it will be added another time, resulting double.
How can I check if File contains already $dbfilename, and if yes, don't add id, or even don't execute the query?
This is not a good way of storing information in a database. But I'll get to that in a second. To directly answer your question, you could use this as your SQL query:
UPDATE TEST SET File = CONCAT(File, '$dbfilename')
WHERE id='$p_id'
AND File NOT LIKE '%$dbfilename%'
AND Lingua='$linguadilavoro'
However, this may cause some issues when one file pineapple.jpg and you try to add another-pineapple.jpg
Really, I think you should consider how this is a horribly bad approach to databases. Consider breaking the files off into a second table. For example:
# a table for the fruit names
CREATE TABLE fruits (
id INT UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(250) NOT NULL,
UNIQUE INDEX(name)
);
# a table for file names
CREATE TABLE files (
fileid INT UNSIGNED NOT NULL DEFAULT PRIMARY KEY AUTO_INCREMENT,
fruitid INT UNSIGNED,
filename VARCHAR(250),
UNIQUE INDEX(fruitid, filename)
);
# find all of the fruits with their associated files
SELECT fruits.id, fruits.name, files.filename
FROM fruits LEFT JOIN files ON fruits.id=files.fruitid
# add a file to a fruit
INSERT INTO files (fruitid, filename)
VALUES ('$fruitID', '$filename')
ON DUPLICATE KEY UPDATE fruitid=LAST_INSERT_ID(id)
You will have to select out the FILE for the id.
then use explode to break it into an array
then check use in_array to determine if it should be added or not
Here is some (untested) code for guidance
$stmt = $link->query("SELECT File File from TEST WHERE id = '$p_id'");
$rec = $stmt->fetchAssoc();
$files = explode(" | ",$rec["FILE"]);
if (!in_array($dbfilename, $files)){
// add to FILE
} else {
// it's already there
}
I would redesign your table structure and add a new table File with the following columns instead of using a varchar field for multiple values:
Table Test
TableId, Name
Table File
FileId, TestId, FileName

PHP & MySQL, Good query is failing

I am having an odd issue with PHP and MySQL.
In attempt to create a table from PHP, I have pasted in the query I need, which executes successfully outside of the PHP environment, into PHP.
$CREATE_PAGES = "DROP TABLE IF EXISTS `MyDatabase`.`pages`;
CREATE TABLE `MyDatabase`.`pages` (
`Page_ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`Page_File` varchar(1000) NOT NULL,
`Page_Description` varchar(1000) NOT NULL,
`Page_Message` longtext NOT NULL,
PRIMARY KEY (`Page_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;";
$result= mysql_query($CREATE_PAGES,$link);
if(!($result)){
echo mysql_error();
echo $CREATE_PAGES;
}
Then I get the standard error message
. . . for the right syntax to use near 'CREATE TABLE `MyDatabase`.`pages` ( `Page_ID` int(10) unsigned NOT NULL' at line 2
However, the odd part is that when I echo the query $CREATE_PAGES I can copy and paste and it will execute just fine. How can it be a syntax error?
I know that it is not a connection error, I can pull data from another table in that database.
Is there something I am missing?
PHP call to mysql_query allows only one action at the time (as a part of SQL injection prvention I guess) so you have to split your query into two parts and call mysql_query twice.
The mysql_query() function can only execute one query at a time, whereas you can execute an arbitrary number at the command line.
From the documentation:
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.
To overcome this:
$dropTable = "DROP TABLE IF EXISTS `MyDatabase`.`pages`";
mysql_query($dropTable, $link);
$createPages ="CREATE TABLE `MyDatabase`.`pages` (
`Page_ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`Page_File` varchar(1000) NOT NULL,
`Page_Description` varchar(1000) NOT NULL,
`Page_Message` longtext NOT NULL,
PRIMARY KEY (`Page_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;";
$result = mysql_query($createPages, $link);
if(!($result)) {
echo mysql_error();
}
From docs to mysql_query:
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.
mysql_query can only execute a single query, it doesn't support execution of multiple queries. It's also recommended to not end your query with a semicolon.
Look for more information in the PHP documentation.

php mysql error for creating a table

I got an error while creating a table in php with mysql database, and I tried testing directly on mysql query engine it works fine. whereas in php code it gives below 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.
Below is the code I am writing
$query14 = mysql_query("create table $tablename (
project_id INT,
project_client_id INT,
project_partner_id INT,
project_manager_id INT,
project_employees INT,
project_name VARCHAR(500),
project_status TEXT,
project_summary LONGTEXT,
project_order INT,
project_start_date DATETIME,
project_end_date DATETIME
) ENGINE = INNODB;");
and below is the image attached and table structure should be and this is the sample table i create using with phpmyadmin interface.
And below is the full 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 ''8' (project_id INT, project_client_id INT, project_partner_id INT, project_mana' at line 1`
I didn't see any problem with your query. But what is the value of $tablename? Two error possibilities here :
The variable $tablename is empty.
$tablename is a key-word.
Please check the above two otherwise its all right.
UPDATE :
As per your updated question please try with the following code. I think it will help you.
$query14 = mysql_query("create table `$tablename` (
`project_id` INT,
`project_client_id` INT,
`project_partner_id` INT,
`project_manager_id` INT,
`project_employees` INT,
`project_name` VARCHAR(500),
`project_status` TEXT,
`project_summary` LONGTEXT,
`project_order` INT,
`project_start_date` DATETIME,
`project_end_date` DATETIME
) ENGINE = INNODB;");
Your query syntax is fine, it looks like $tablename is empty.
I think the issue is what is getting replaced for $tablename.
Having the full code example would be more useful in debugging the error.
The mysql create statement works just fine here on mysql 5.1.58 .
As you said in above comments that after echoing the $tablename you got the value 8 then it is not possible to create table.
you have to rename the value of $tablename like tbl_8.
remember with the name tbl-8 your also got error,,
The problem is, $tablename is 8 currently and for SQL table, table name must start with a letter. Current tablename is invalid.

PHPbb DBAL refuses to Execute Correct PHP and SQL

chances are if you are seeing this you most likely saw my last question.
So from there I have made progress. I have realized that the SQL is fine and that it is the PHPbb's DBAL that is causing problems. I sould also note that I am using usercake which initiates the dbal class and all that. For some reason the following code works:
$sql = "CREATE TABLE ideas(
id int(10) unsigned NOT NULL auto_increment,
`user` tinytext NOT NULL,
`date` int(10) unsigned NOT NULL default '0',
description text NOT NULL,
upvotes text NOT NULL,
downvotes text NOT NULL,
appreciated tinyint unsigned NOT NULL default '0',
ip tinytext NOT NULL,
PRIMARY KEY (id))";
$temp = $db->sql_query($sql);
die($temp);
But this code doesn't:
$sql = "INSERT INTO `FUideas` (`description`) VALUES ('TESTER')";
$temp = $db->sql_query($sql);
die($temp);
For information on the FUideas table see my previous post.
I know the sql works because it executes if I use plain php:
$con = mysql_connect('localhost', 'name', 'password');
mysql_select_db("db", $con);
$sql = "INSERT INTO `concepts` (`description`) VALUES ('TESTER')";
mysql_query($sql,$con) or die(mysql_error());
Any ways to fix this are much appreciated
If you need any more information just ask, also I will be online, so if you want to attempt a test just post the code and I will try it.
Edit
So I get it to work if I fill out the other fields with either a 0 or '', can anyone explain this behavior?
It seems as though you're creating a table named ideas and then trying to inser into a table named FUideas. Has FUideas been created elsewhere? In any case, try die(mysql_error()); to see if the error is with the query itself.

Categories