Is it necessary to mysql real escape when using alter table? - php

I noticed the other day that I cannot bind variables when using PDO with ALTER TABLE for example the following example will not work,
$q = $dbc -> prepare("ALTER TABLE emblems ADD ? TINYINT(1) UNSIGNED NOT NULL DEFAULT '0', ADD ? DATETIME NOT NULL");
$q -> execute(array($emblemDB, $emblemDB . 'Date'));
So is it necessary to use mysql_real_escape string and do it like below,
// ESCAPE NAME FOR MYSQL INSERTION
$emblemDB = mysql_real_escape_string($emblemDB);
// INSERT EMBLEM DETAILS INTO DATABASE
$q = $dbc -> prepare("ALTER TABLE emblems ADD " . $emblemDB . " TINYINT(1) UNSIGNED NOT NULL DEFAULT '0', ADD " . $emblemDB . "Date DATETIME NOT NULL");
$q -> execute();
Or do I not need to add in mysql_real_escape_string? As the only thing the query can do is ADD columns?
Thanks

Depends. If you directly use user input in your query, you should use it. If you don't, the user could delimit the query and throw a DROP statement after it.
When a user would input:
somekindofname TINYINT(1) UNSIGNED NOT NULL DEFAULT '0'; DROP TABLE emblems --
Your query would become:
ALTER TABLE emblems ADD somekindofname TINYINT(1) UNSIGNED NOT NULL DEFAULT '0'; DROP TABLE emblems -- TINYINT(1) UNSIGNED NOT NULL DEFAULT '0', ADD TINYINT(1) UNSIGNED NOT NULL DEFAULT '0' somekindofname; DROP TABLE emblems -- Date DATETIME NOT NULL
Your database will execute the ALTER TABLE, execute the DROP TABLE and ignore the comment at the end.

Related

Getting error while running the mysql query to create table

I am getting one error while creating table using MySQL. I am explaining my query below.
$sql="CREATE TABLE db_cron( ".
"id INT NOT NULL AUTO_INCREMENT, ".
"user_alert INT(11) NOT NULL DEFAULT NONE, ".
"status INT(11) NOT NULL DEFAULT NONE, ".
"PRIMARY KEY ( id )); ";
I am getting the below error:
#1064 - 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 'NONE, status INT(11) NOT NULL DEFAULT NONE, PRIMARY KEY ( id ))'
at line 1
Here I need to create table with default value as none.
You have used too many quotes just to connect multiple string, it does not required.
Please remove those quotes and you also have to provide default value instead of NULL something like 0 OR any other value that you want.
However you can use below query to create table.
$sql = "CREATE TABLE `db_cron`( id INT NOT NULL AUTO_INCREMENT,
user_alert INT(11) NOT NULL DEFAULT 0,
status INT(11) NOT NULL DEFAULT 0,
PRIMARY KEY ( id ))";
above query will create table with default value 0 for user_alert and status
Hope this will helps you
Thanks & Regards.
1.You have applied unnecessary quotes.
2.You have NOT NULL along with DEFAULT NONE, which is not going to happen(You have to provide some value as default when using NOT NULL)
Do like below:-
$sql="CREATE TABLE db_cron(
id INT(11) NOT NULL AUTO_INCREMENT,
user_alert INT(11) NOT NULL DEFAULT 0,
status INT(11) NOT NULL DEFAULT 0,
PRIMARY KEY ( id )
)";

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

Php PDO: Why does Inserting NULL yields to 0 [duplicate]

This question already has answers here:
Insert NULL instead of empty string with PDO
(3 answers)
Closed last month.
I searched any possible help that can be found online but still the problem with INSERT NULL using PHP PDO persists.
The script is a csvupload script originally came from here Import CSV into MySQL
To make the story short, Let me present the possible cause..
if($linearray[4]=='Unknown')
$linearray[4]=null;
$linemysql = implode("','",$linearray);
$linemysql = "'".$linemysql."'";
$setsu->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$tsuika = $setsu->prepare("INSERT INTO tablename (SubAgentID, BookID, AgentID, SubAgentName, Risk, Area, CurrentBalance) VALUES ($linemysql)");
$tsuika -> bindValue(':Risk', null, PDO::PARAM_INT);
$tsuika ->execute();
Looking the code above, I explicitly set the field values on the prepare statment.
On phpmyadmin the Risk field accepts NULL, set the default value to NULL, and has no problems. But when doing INSERT with PHP the value it gets is 0. Why?
Before Inserting, I echoed it and if the field $linearray[4] contains Unknown, it converts it to NULL yielding, '' for that part.
table structure
CREATE TABLE IF NOT EXISTS `subagentdb` (
`SubAgentID` int(10) NOT NULL AUTO_INCREMENT,
`BookID` int(10) NOT NULL,
`AgentID` int(10) NOT NULL,
`SubAgentName` varchar(30) NOT NULL,
`Risk` float DEFAULT NULL,
`Area` varchar(20) NOT NULL,
`CurrentBalance` float NOT NULL,
PRIMARY KEY (`SubAgentID`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=1 ;
You're binding the value explicitly as PDO::PARAM_INT. Whatever value you pass will be cast to an int because of that. null casts to 0.
To actually bind an SQL NULL value, you need to bind the value as PDO::PARAM_NULL.
just use PDO::PARAM_NULL instead of PDO::PARAM_INT ? I think the NULL is converted to 0 (INT) instead of null value
If you back-up a and then restore the table, the null value becomes 0. The only way I found to correct this is after the create table, add "UPDATE table SET foo to null WHERE foo = 0".

Why CREATE TABLE IF NOT EXISTS always returns false?

i don't know what i am doing wrong here but i have been trying to get this to work for hours. i just want it to create a table that doesn't exist. i made it as simple as i can make it and still it just returns false and doesn't change anything. please let me what i am doing wrong thank you in advance.
$conn=mysql_connect('localhost:3306', 'root', '');
mysql_select_db("test",$conn);
$sql = "CREATE TABLE IF NOT EXISTS 'works' (
`autoPlace` int(11) unsigned NOT NULL auto_increment,
`element` float(255) NOT NULL,
`month` tinyint(4) NOT NULL ,
`mday` tinyint(4) NOT NULL ,
`wday` char(12) NOT NULL ,
`time` smallint(6) NOT NULL,
PRIMARY KEY (`autoPlace`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8";
$thisKeepsReturningFalse= mysql_query($sql);
var_dump($thisKeepsReturningFalse);
When I tried to execute your query I got this error:
Incorrect column specifier for column 'element'
The problem is float(255) is not a valid declaration
It needs to be float(x) where x<=53, or you can use float(x,y) - see mysql docs here
Also, as pointed out in the comments, you have single quotes around works. Remove them or replace them with backticks.
After fixing these errors, I was able to successfully execute your query.
"CREATE" command in MySQL is not return value command so that it always return false(not like SELECT). To check if the command "CREATE" success or not, you can use "SHOW TABLES" to check after executing the "CREATE" command.
When you create a float element you must specify the decimals with a comma.And also the name of the table can't be with this format '' it must to be inside ``.
So in this example the query should be :
CREATE TABLE IF NOT EXISTS `works`
(
`autoPlace` int(11) unsigned NOT NULL auto_increment,
`element` float(255,0) NOT NULL,
`month` tinyint(4) NOT NULL ,
`mday` tinyint(4) NOT NULL ,
`wday` char(12) NOT NULL ,
`time` smallint(6) NOT NULL,
PRIMARY KEY (`autoPlace`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8
Note how the float it's float(255,0) and not just 255. You must set this , 0 is the default

create and insert in a single query

<?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

Categories