values are not inserting - php

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

Related

Why is MySql not storing boolean value with php

I have a database table with two columns that have been set as boolean. Whenever I store something in the table everything works correctly except the boolean columns are always false. The columns are featured post and published.
I am using php 7.1.1 and MariaDB 10.1.21 on my xampp local installation.
Output of show table:
CREATE TABLE `posts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL,
`content` text NOT NULL,
`seo_description` varchar(255) NOT NULL,
`featured_post` tinyint(1) NOT NULL DEFAULT '0',
`published` tinyint(1) NOT NULL DEFAULT '0',
`seo_title` varchar(255) NOT NULL,
`post_type` enum('blog','product') NOT NULL,
`featured_image_id` int(11) NOT NULL,
`category_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `title` (`title`),
UNIQUE KEY `seo_title` (`seo_title`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=latin1 ROW_FORMAT=COMPACT
Php code defining onr of the variables, the other is exactly the same:
if(isset($_POST["published"])){
$published = sanitizeInput($_POST["published"]);
if($published){ //test to see if correct values where being sent and they were
echo json_encode("boolean true");
} else {
echo json_encode("boolean false");
}
} else {
$published = false;
}
$query = "insert into posts "
. "(title, content, seo_description, featured_post, published, seo_title, post_type, category_id) "
. "values "
. "(:title, :content, :seo_description, :featured_post, :published, :seo_title, :post_type, :category_id)";
$stmt = $pdo->prepare($query);
$stmt->bindValue("featured_post", $featuredPost, PDO::PARAM_BOOL);
$stmt->bindValue("published", $published, PDO::PARAM_BOOL);
$stmt->bindValue("title", $title);
$stmt->bindValue("content", $content);
$stmt->bindValue("seo_description", $seoDescription);
$stmt->bindValue("seo_title", $seoTitle);
$stmt->bindValue("post_type", $postType);
$stmt->bindValue("category_id", $categoryId);
$stmt->execute();
Any help would be much appreciated.
Thanks in advance

Can't execute multi-statement SQL through PHP code [duplicate]

This question already has answers here:
How to execute two mysql queries as one in PHP/MYSQL?
(8 answers)
Closed 8 years ago.
The SQL code used below works just fine if pasted in PHPMyAdmin.
But once I use it in custom PHP code it throws an exception:
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 v2_session ( username varchar(150) DEFAULT '', time
varchar(1' at line 2
What am I missing, the code is dead simple, I am so confused right now.
This is my PHP code:
$con=mysqli_connect("host","user","password","db");
if (mysqli_connect_errno()) {
echo "Error: " . mysqli_connect_error();
}
$sql="
DROP TABLE IF EXISTS v2_session;
CREATE TABLE v2_session (
username varchar(150) DEFAULT '',
time varchar(14) DEFAULT '',
session_id varchar(200) NOT NULL DEFAULT '0',
guest tinyint(4) DEFAULT '1',
userid int(11) DEFAULT '0',
usertype varchar(50) DEFAULT '',
gid tinyint(3) unsigned NOT NULL DEFAULT '0',
client_id tinyint(3) unsigned NOT NULL DEFAULT '0',
data longtext,
PRIMARY KEY (session_id(64)),
KEY whosonline (guest,usertype),
KEY userid (userid),
KEY time (time)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;";
if (mysqli_query($con,$sql)) {
echo 'Success!';
} else {
echo "Error: " . mysqli_error($con);
}
mysqli_close($con);
mysqli_query does not allow for multiple statements concatenated by a semicolon.
Either split the query up into two separate queries, or use mysqli_multi_query() with a very similar syntax instead.
bool mysqli_multi_query ( mysqli $link , string $query )
Executes one or multiple queries which are concatenated by a semicolon.
The downside with mysqli_multi_query is that it makes your code more sensitive to SQL injection (since a whole statement can be injected), but for static queries without parameters it should not cause any problems.
These are two statements, and should be executed separately:
$sql = "DROP TABLE IF EXISTS v2_session";
if (!mysqli_query($con,$sql)) {
echo "Error: " . mysqli_error($con);
exit(1);
}
$sql="
CREATE TABLE v2_session (
username varchar(150) DEFAULT '',
time varchar(14) DEFAULT '',
session_id varchar(200) NOT NULL DEFAULT '0',
guest tinyint(4) DEFAULT '1',
userid int(11) DEFAULT '0',
usertype varchar(50) DEFAULT '',
gid tinyint(3) unsigned NOT NULL DEFAULT '0',
client_id tinyint(3) unsigned NOT NULL DEFAULT '0',
data longtext,
PRIMARY KEY (session_id(64)),
KEY whosonline (guest,usertype),
KEY userid (userid),
KEY time (time)
) ENGINE=MyISAM DEFAULT CHARSET=utf8";
if (mysqli_query($con,$sql)) {
echo 'Success!';
} else {
echo "Error: " . mysqli_error($con);
}

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

PDO not inserting more than one row in table

I'm having trouble inserting image data into my database. I have a table called images. When dumped with PHPMyAdmin it looks like this:
CREATE TABLE IF NOT EXISTS `images` (
`id` int(11) NOT NULL,
`orig_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`hash` varchar(6) COLLATE utf8_unicode_ci NOT NULL,
`filename` varchar(12) COLLATE utf8_unicode_ci NOT NULL,
`uploaded` datetime NOT NULL,
`views` int(11) NOT NULL DEFAULT '0',
`album_id` int(11) DEFAULT NULL,
`user_id` int(11) DEFAULT NULL,
`server_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`),
KEY `server_id` (`server_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
This is the code I'm using to insert rows:
// Database connection
$db = new PDO('mysql:host=localhost;dbname=testdb', 'root', '');
// some code...
$st = $db->prepare('INSERT INTO `images` (orig_name, hash, filename, uploaded, server_id)
VALUES (?, ?, ?, ?, (SELECT `id` FROM `servers` WHERE `name` = ?))');
$st->execute(array($origName, $fileHash, $filename, date('c'), $server));
// more code...
// Database cleanup
$st = null;
$db = null;
The script returns no errors, and works flawlessly for the first row inserted. If the script runs again, it fails to insert any more rows in the images table. I see no reason why it'd behave like this, the data going into each field is unique each time (except for the server_id field).
Your id field isn't set to auto_increment.
The first record that you post will be added, with a NULL as id; the second record won't be added because there's already a record with NULL as the primary key, so it'll fail - you don't have any error checking in the code, so it won't be printing out the errors it's getting back.

Why mysql_insert_id returns 0 in my case?

This is my table:
CREATE TABLE `users` (
`id` int(10) unsigned NOT NULL auto_increment,
`name` varchar(20) NOT NULL default '',
`pass` varchar(32) NOT NULL default '',
`lang` varchar(2) default NULL,
`locale` varchar(2) default NULL,
`pic` varchar(255) default NULL,
`sex` char(1) default NULL,
`birthday` date default NULL,
`mail` varchar(64) default NULL,
`created` timestamp NOT NULL default CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `mail` (`mail`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=27 ;
And this is my query:
$query = "INSERT IGNORE INTO `users` (`name`, `mail`, `birthday`, `lang`, `locale`, `sex`, `pic`) VALUES ('".$name."', '".$email."', '".date_format($birthdaynew, 'Y-m-d H:i:s')."', '".substr($locale, 0, 2)."', '".substr($locale, -2, 2)."', '".$sex."', 'pic/".$uid.".jpg')";
$rows = mysql_query($query) or die("Failed: " . mysql_error());
$_SESSION['id'] = mysql_insert_id(); // I have tryed also mysql_insert_id($db_con) where $db_con is the link to db.
$_SESSION['name'] = $name;
$_SESSION['name'] contains correctly the name but $_SESSION['id'] contains 0.
Why ?
I'm going crazy!
Is there a particular reason why you are using INSERT IGNORE?
If you use INSERT IGNORE, then the row won't actually get inserted if there is a duplicate key (PRIMARY or UNIQUE), or inserting a NULL into a column with a NOT NULL constraint.
Referring to the pass column, as you have not defined anything to insert into it, and it has NOT NULL constraint.
EDIT:
Referring also to the mail column, as you have a UNIQUE constraint on it.

Categories