Why is MySql not storing boolean value with php - 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

Related

Mysqli prepared insert with nested selects fails in foreach

I'm trying to insert some date to MySQL table with prepared insert with nested 3 nested selects in it. The thing is that for all nested selects a single variable is used. Actual SQL:
INSERT INTO db_test.offers
(`id`,`catalog_service_id`,`offer_name`,
`offer_description`,`offer_url`,
`offer_interaction_format`,`offer_methods`)
VALUES(1,
(SELECT `catalog_service_id` FROM db_test.catalog_services
WHERE `catalog_service_code` = ?),
(SELECT `catalog_service_name` FROM db_test.catalog_services
WHERE `catalog_service_code` = ?),
(SELECT `catalog_service_name` FROM db_test.catalog_services
WHERE `catalog_service_code` = ?),
'https://url.com', 'json', 'CC');
PHP code:
class test extends mysqli{
function db_action($host = null){
$mysqli = new mysqli($host, MYSQL_USER, MYSQL_PASS, "db_test");
if(!$mysqli){
die ("couldn't connect to mysql host" . mysqli_connect_error());
}
$codes= ["AAAAA005760000000001","ААААА032680000000001","ААААА032680000000002"];
$query="SQL code from above";
$stmt = $mysqli->prepare($query);
$stmt ->bind_param("sss", $offer, $offer, $offer);
foreach ($codes as $k => $offer) {
if($stmt->execute() === false){
print 'Wrong SQL. Error: ' . $stmt->error . "\r\n";
}else{
$last_inserted_id = $mysqli->insert_id;
print "Insert row with id: " . $last_inserted_id . " for service_code: ". $offer . "\r\n";
}
}
$stmt->close();
}
}
First iteration of foreach works fine (1 row is inserted with correct data), but on 2nd and 3rd (just for an example, real number of elements in $codes array is unknown). The The executed statement on the sql-server is executed with question marks instead of actual value. When I go through the function in debugger - the value of $offer var changes on each iteration of for each.
SQL error that comes from the server is obvious: catalog_service_id cannot be null.
table info:
CREATE TABLE `offers` (
`offer_id` int(11) NOT NULL AUTO_INCREMENT,
`id` int(11) NOT NULL,
`catalog_service_id` int(11) NOT NULL,
`offer_name` varchar(255) DEFAULT NULL,
`offer_description` varchar(1000) DEFAULT NULL,
`offer_create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`offer_start_time` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`offer_stop_time` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`offer_url` varchar(256) NOT NULL,
`offer_auth` enum('Basic','Digest') DEFAULT NULL,
`offer_auth_name` varchar(255) DEFAULT NULL,
`offer_auth_password` varchar(255) DEFAULT NULL,
`offer_auth_secret` varchar(255) DEFAULT NULL,
`offer_operator_id` int(11) NOT NULL,
`public_offer_url` varchar(1000) NOT NULL,
`offer_interaction_format` enum('urlencoded','json') NOT NULL DEFAULT 'urlencoded',
`offer_methods` enum('CC','MC') NOT NULL DEFAULT 'MC',
`offer_inn` varchar(20) DEFAULT NULL,
`offer_kpp` varchar(20) DEFAULT NULL,
`offer_min` int(11) DEFAULT NULL,
`offer_max` int(11) DEFAULT NULL,
PRIMARY KEY (`offer_id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8
I'm really stuck...

msqli prepared query not working

I have this table:
CREATE TABLE `comment` (
`id` int(11) unsigned NOT NULL,
`name` varchar(255) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`comment` text,
`article_id` int(11) unsigned NOT NULL DEFAULT '1',
`date` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`deleted` tinyint(3) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
This is in the table:
INSERT INTO `comment` VALUES (0,'Bernard','user#domain.com','This is a comment',1,'2014-07-22 17:34:24',0);
This php code spits out "foo" and nothing else:
<?php
error_reporting(E_ALL);
echo 'foo';
$db = new mysqli("localhost", 'root', '', 'ggs');
$query = $db->prepare("SELECT * FROM `comment` `c` WHERE `c`.`article_id` = ? AND `c`.`deleted` = 0 ORDER BY `c`.`date` ASC");
if (!$query) {
echo $db->errno . " - Could not prepare SQL statement: " . $db->error;
} else {
$query->bind_param('i', 1);
$query->execute();
echo json_encode($query->fetch());
}
echo 'bar';
Why is this failing, and why is it not throwing any errors?
As for the query, you should replace the first 0 a null to let the auto-increment work:
INSERT INTO `comment` VALUES (NULL,'Bernard','user#domain.com','This is a comment',1,'2014-07-22 17:34:24',0);

SQL Database trouble

I'm trying to create a database with 4 tables. When I run my code, it creates the first table but not the other 3. It's because of the second table not changing the storage engine to myISAM, but I can't figure out why it's not doing this. Here is my code:
<?php
require_once 'conn.php';
$sql= <<<EOS
CREATE TABLE IF NOT EXISTS cms_access_levels (
access_lvl tinyint(4) NOT NULL auto_increment,
access_name varchar(50) NOT NULL default'',
PRIMARY KEY(access_lvl)
)
EOS;
$result= mysql_query($sql) or
die(mysql_error());
$sql= "INSERT IGNORE INTO cms_access_levels " .
"VALUES(1, 'Users'), " .
"(2, 'Moderator'), " .
"(3, 'Administrator')";
$result= mysql_query($sql) or
die(mysql_error());
$sql= <<<EOS
CREATE TABLE IF NOT EXISTS cms_articles ENGINE = MYISAM (
article_id int(11) NOT NULL auto_increment,
author_id int(11) NOT NULL default '0',
is_published tinyint(11) NOT NULL default '0',
date_submitted datetime NOT NULL default '0000-00-00 00:00:00',
date_published datetime NOT NULL default '0000-00-00 00:00:00',
title varchar(255) NOT NULL default '',
body mediumtext NOT NULL,
PRIMARY KEY(article_id),
KEY IdxArticle(author_id, date_submitted),
FULLTEXT KEY IdxText(title, body)
)
EOS;
$result= mysql_query($sql) or
die(mysql_error());
$sql= <<<EOS
CREATE TABLE IF NOT EXISTS cms_comments (
comment_id int(11) NOT NULL auto_increment,
article_id int(11) NOT NULL default '0',
comment_date datetime NOT NULL default '0000-00-00 00:00:00',
comment_user int(11) NOT NULL default '0',
comment text NOT NULL,
PRIMARY KEY(comment_id),
KEY idxComment(article_id)
)
EOS;
$result= mysql_query($sql) or
die(mysql_error());
$sql= <<<EOS
CREATE TABLE IF NOT EXISTS cms_users (
user_id int(11) NOT NULL auto_increment,
email varchar(255) NOT NULL default '',
password varchar(50) NOT NULL default '',
name varchar(100) NOT NULL default '',
access_lvl tinyint(4) NOT NULL default '1',
PRIMARY KEY(user_id),
UNIQUE KEY uniq_email(email)
)
EOS;
$result= mysql_query($sql) or
die(mysql_error());
$adminemail= "aolle570#uwsp.edu";
$adminpass= "graysen7";
$adminname= "olle";
$sql= "INSERT INTO cms_users " .
"VALUES (NULL, '$adminemail', '$adminpass', '$adminname', 3)";
$result= mysql_query($sql) or
die(mysql_error());
echo "<html><head><title>CMS Tables Created</title></head><body>";
echo "CMS Tables created. Here is the initial login information: <br />";
echo "<ul><li><strong>Login:</strong> " . $adminemail . "</li><br />";
echo "<li><strong>Password:</strong> " . $adminpass . "</li><br />";
echo "<a href='login.php'>Login</a> to the site now.";
echo "</ul></body></html>";
?>
Any help is greatly appreciated!
As far as I know, and my database tells me I am right, engine should be mentioned after create definition. Try this:
CREATE TABLE IF NOT EXISTS cms_articles (
article_id int(11) NOT NULL auto_increment,
author_id int(11) NOT NULL default '0',
is_published tinyint(11) NOT NULL default '0',
date_submitted datetime NOT NULL default '0000-00-00 00:00:00',
date_published datetime NOT NULL default '0000-00-00 00:00:00',
title varchar(255) NOT NULL default '',
body mediumtext NOT NULL,
PRIMARY KEY(article_id),
KEY IdxArticle(author_id, date_submitted),
FULLTEXT KEY IdxText(title, body)
) ENGINE = MYISAM
You should put the ENGINE = MYISAM after the field definition's closing parenthesis.
http://dev.mysql.com/doc/refman/5.1/en/create-table.html
shows table_options are after create definition.

MySQL delete troubleshooting

I restarted the MySQL service and I attempted to use my PHP programs delete function to delete an existing row but I'm finding although the delete queries were counted the row was not deleted. I tried applying on delete cascade to the foreign key of the child table but that did not seem to have an effect. I'm wondering why the delete would be doing nothing.
CREATE TABLE `customers` (
`idcustomers` int(11) NOT NULL AUTO_INCREMENT,
`firstname` varchar(45) DEFAULT NULL,
`lastname` varchar(45) DEFAULT NULL,
`address1` varchar(45) DEFAULT NULL,
`address2` varchar(45) DEFAULT NULL,
`city` varchar(45) DEFAULT NULL,
`state` varchar(45) DEFAULT NULL,
`zip` varchar(45) DEFAULT NULL,
`phone` varchar(45) DEFAULT NULL,
`email` varchar(45) DEFAULT NULL,
`cell` varchar(45) DEFAULT NULL,
PRIMARY KEY (`idcustomers`),
UNIQUE KEY `idcustomers_UNIQUE` (`idcustomers`)
) ENGINE=InnoDB AUTO_INCREMENT=54 DEFAULT CHARSET=latin1
CREATE TABLE `events` (
`idevents` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(250) DEFAULT NULL,
`start` datetime DEFAULT NULL,
`end` datetime DEFAULT NULL,
`allday` varchar(50) DEFAULT NULL,
`url` varchar(1000) DEFAULT NULL,
`customerid` int(11) NOT NULL,
`memo` longtext,
`dispatchstatus` varchar(45) DEFAULT NULL,
PRIMARY KEY (`idevents`),
KEY `FK_events` (`customerid`),
CONSTRAINT `FK_events` FOREIGN KEY (`customerid`) REFERENCES `customers` (`idcustomers`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=latin1
Com_delete 2
The PHP looks like this:
<?php
session_start();
date_default_timezone_set("America/Los_Angeles");
if($_SESSION['loggedin'] != TRUE)
{
header("Location: index.php");
}
require_once('../php.securelogin/include.securelogin.php');
$mysqli = new mysqli($ad_host, $ad_user, $ad_password, "samedaycrm");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$customerid = $_SESSION['customer_id'];
$tSQL = "delete from events where customerid = \"$customerid\"";
$result = $mysqli->query($tSQL);
$tSQL = "delete from customers where idcustomers = \"$customerid\"";
$result = $mysqli->query($tSQL);
echo $mysqli->error;
?>
Assuming that the customerid and idcustomers columns are both numeric it should be fine. You should not need to quote the variables in those queries btw, then you wouldnt need to escape them. You may try:
$tSQL = "delete from events where customerid = $customerid";
but it should not be any different than what you used already. Of course if you are not sure of the type of the column you can use:
$tSQL = "delete from events where customerid = '".$customerid."'";
or you can get away with:
$tSQL = "delete from events where customerid = '$customerid'";
but I have always hated that for some reason.
if all of that fails troubleshoot by spitting out the $customerid (or even the whole $tSQL) variable and then trying the query manually in phpmyadmin or toad or whatever db client you use, and see what it tells you. If it just says 0 rows affected, then run it like a select instead. Tailor to fit.

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