msqli prepared query not working - php

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);

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

mysql MAX() returns 0 instead of actual value

The following code returns 0 instead of the biggest number from the row order_id
if ($result_oid = $link->prepare("SELECT MAX(order_id) AS order_id FROM $table")) {
$result_oid->execute();
$obj = $result_oid->get_result()->fetch_object();
$oid_o = $obj->id;
$result_oid->close();
$oid = $oid_o + 1;
}
Here is a working example using the PHP mysql instead of mysqli (with the same mysql database):
mysql_connect($host, $user, $pwd) or die ("Couldn't connect to MySQL database.");
mysql_select_db($db) or die ("No Database found!");
$query = mysql_query('SELECT MAX(order_id) FROM airsale_list');
$result = mysql_fetch_array($query, MYSQL_NUM);
$max_order_id = $result[0];
$max_order_id = (int)$max_order_id;
$oid = $max_order_id++;
echo "<h4>order_id: $oid</h4>";
mysql_close();
Table structure
CREATE TABLE IF NOT EXISTS `airsale_list` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`cat` int(11) NOT NULL,
`title` varchar(255) NOT NULL,
`desc_small` varchar(1000) DEFAULT NULL,
`name` varchar(255) NOT NULL,
`lastupdate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`price` int(20) NOT NULL,
`currency` varchar(3) NOT NULL DEFAULT 'EUR',
`total_time` varchar(255) DEFAULT NULL,
`engine` varchar(1000) DEFAULT NULL,
`engine_time` varchar(255) DEFAULT NULL,
`prop` varchar(1000) DEFAULT NULL,
`prop_time` varchar(255) DEFAULT NULL,
`exterior` varchar(2000) DEFAULT NULL,
`interior` varchar(2000) DEFAULT NULL,
`avionics` varchar(5000) DEFAULT NULL,
`add_info` varchar(5000) DEFAULT NULL,
`order_id` int(20) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=103;
I think you should be using $obj->order_id instead of $obj->id since you are grabbing the maximum value as order_id in the query.
if ($result_oid = $link->prepare("SELECT MAX(order_id) AS order_id FROM $table")) {
$result_oid->execute();
$obj = $result_oid->get_result()->fetch_object();
$oid_o = $obj->order_id;
$result_oid->close();
$oid = $oid_o + 1;
}

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.

mysqli multi query not executing the queries

I am trying to execute 3 queries to create tables within a database but it will not execute the query giving me a syntax error. Can anyone look at this code and tell me what I typed wrong to make this work? I have tried everything and I can not get the queries to execute!
$dh = mysqli_connect($_POST['hostname'], $_POST['username'], $_POST['password'], $_POST['database']);
if(! $dh )
{
die('Could not connect: ' . mysql_error());
}
echo "Connected successfully...<br /><br />";
$query = "CREATE TABLE IF NOT EXISTS `content` (
`content_id` INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`section_id` INT(11) NOT NULL,
`header` VARCHAR(255) NOT NULL,
`sub_header` VARCHAR(255) NOT NULL,
`date_range` VARCHAR(64) NOT NULL,
`content_body` TEXT NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1";
$query .= "CREATE TABLE IF NOT EXISTS `sections` (
`section_id` INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`title` VARCHAR(255) NOT NULL,
`position` INT(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1";
$query .= "CREATE TABLE IF NOT EXISTS `sections` (
`user_id` INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`username` VARCHAR(32) NOT NULL,
`password` VARCHAR(32) NOT NULL,
`first_name` VARCHAR(32) NOT NULL,
`last_name` VARCHAR(32) NOT NULL,
`email` VARCHAR(1024) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1";
$retval = mysqli_multi_query($dh, $query);
You don't have semi colons between the queries and you are joining them all together and running at once.
If you are running multiple queries like that you need semicolons at the end of each query
$query = "CREATE TABLE IF NOT EXISTS `content` (
`content_id` INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`section_id` INT(11) NOT NULL,
`header` VARCHAR(255) NOT NULL,
`sub_header` VARCHAR(255) NOT NULL,
`date_range` VARCHAR(64) NOT NULL,
`content_body` TEXT NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;";
$query .= "CREATE TABLE IF NOT EXISTS `sections` (
`section_id` INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`title` VARCHAR(255) NOT NULL,
`position` INT(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;";
$query .= "CREATE TABLE IF NOT EXISTS `sections` (
`user_id` INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`username` VARCHAR(32) NOT NULL,
`password` VARCHAR(32) NOT NULL,
`first_name` VARCHAR(32) NOT NULL,
`last_name` VARCHAR(32) NOT NULL,
`email` VARCHAR(1024) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;";
You are missing semicolons between queries.
So you are trying to execute something like this: <...> ENGINE=InnoDB DEFAULT CHARSET=latin1CREATE TABLE <...>

Recipe Finder with PHP and MySQL based on Ingredients

I am developing a cooking recipe-website and i want to create a recipe finder based on the used incredients.
My current finder only works with 3 ingredients right.
The Finder should return the right recipe(s) based on the used incredients (should work with 1-n*)
My Tables:
CREATE TABLE IF NOT EXISTS `INGREDIENTS` (
`ingredients_id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(45) NOT NULL,
PRIMARY KEY (`ingredients_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=17 ;
CREATE TABLE IF NOT EXISTS `INGREDIENTS_POS` (
`ingredients_pos_id` int(11) NOT NULL AUTO_INCREMENT,
`ingredients_id` int(11) NOT NULL,
`ingredients_unit` varchar(20) NOT NULL,
PRIMARY KEY (`ingredients_pos_id`),
KEY `ingredients_detail_fk` (`ingredients_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=17 ;
CREATE TABLE IF NOT EXISTS `RECIPES` (
`recipes_id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(50) COLLATE utf8_bin NOT NULL,
`text` varchar(2000) COLLATE utf8_bin NOT NULL,
`count_persons` int(11) NOT NULL,
`duration` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`date` datetime NOT NULL,
`accepted` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`recipes_id`),
KEY `recipes_user_fk` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=88 ;
CREATE TABLE IF NOT EXISTS `RECIPES_POS` (
`recipes_pos_id` int(11) NOT NULL AUTO_INCREMENT,
`recipes_id` int(11) NOT NULL,
`ingredients_id` int(11) NOT NULL,
`ingredients_value` int(11) NOT NULL,
PRIMARY KEY (`recipes_pos_id`),
KEY `recipe_pos_rec_id` (`recipes_id`),
KEY `recipes_pos_ingredient_fk` (`ingredients_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=58 ;
My buggy Solution (doesn't support count from 1-n):
<?php
include 'db_connect.php';
$q = urldecode(mysql_real_escape_string($_GET['q']));
$parameter = explode ('$',$q);
$var = 0;
//print_r($parameter);
foreach($parameter as $ing)
{
//echo $ing;
$sql = "SELECT ingredients_id FROM INGREDIENTS WHERE name='".$ing."'";
$result = mysql_query($sql,$db) or exit('{"Data":null,"Message":null,"Code":500}');
$row = mysql_fetch_array($result);
$arr_id[$var] = $row['ingredients_id'];
$var++;
}
//print_r($arr_id);
$sql = "SELECT r.recipes_id FROM RECIPES r, RECIPES_POS rp WHERE r.recipes_id = rp.recipes_id ";
foreach($arr_id as $id)
{
$sql .= "AND rp.ingredients_id =".$id . " ";
}
//echo $sql;
$result = mysql_query($sql,$db) or exit('{"Data":null,"Message":null,"Code":500}');
mysql_close($db);
$rec;
while($row = mysql_fetch_array($result))
{
//echo "test";
$_GET['id'] = $row['recipes_id'];
$rec= include('get_recipe_byID.php');
}
//print_r(mysql_fetch_array($result));
if (count($arr_id) == 0)
{
echo '{"Data":null,"Message":null,"Code":404}';
die();
}
?>
I need a better solution for that chase.
Maybe SQL itself will help me to find the right recipes
thx
That query helped me a lot:
select r.recipes_id
from RECIPES r
inner join RECIPES_POS rp on r.recipes_id = rp.recipes_id
where rp.ingredients_id in (4, 6)
group by r.recipes_id
having count(distinct rp.ingredients_id) = 2

Categories