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.
Related
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
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);
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.
When registering my first user in table 'users' the id is the same value as user_id in the linking table,1, (language). However, when I register another user (id2 in users) the user_id in language is still 1. See SQL:
CREATE TABLE `language` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`native` varchar(30) NOT NULL,
`other` varchar(30) NOT NULL,
`other_list` varchar(9) NOT NULL,
`other_read` varchar(9) NOT NULL,
`other_spokint` varchar(9) NOT NULL,
`other_spokprod` varchar(9) NOT NULL,
`other_writ` varchar(9) NOT NULL,
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`md5_id` varchar(200) NOT NULL,
`full_name` tinytext CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
`user_name` varchar(10) NOT NULL,
`user_email` varchar(30) NOT NULL,
`user_level` tinyint(4) NOT NULL DEFAULT '1',
`pwd` varchar(220) NOT NULL,
`nationality` varchar(30) NOT NULL,
`department` varchar(20) NOT NULL,
`birthday` date NOT NULL,
`date` date NOT NULL DEFAULT '0000-00-00',
`users_ip` varchar(200) NOT NULL,
`activation_code` int(10) NOT NULL DEFAULT '0',
`banned` int(1) NOT NULL,
`ckey` varchar(200) NOT NULL,
`ctime` varchar(220) NOT NULL,
`approved` int(1) NOT NULL DEFAULT '1',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
This is my PHP code:
if(empty($_SESSION['$user_id'])) { // user not logged in; redirect to somewhere else }
if (!empty($_POST['doLanguage']) && $_POST['doLanguage'] == 'Submit')
{
$result = mysql_query("SELECT `id` FROM users WHERE `banned` = '0'") or
die (mysql_error());
list($id) = mysql_fetch_row($result);
session_start();
$_SESSION['user_id']= $id;
sql_insert = "INSERT into `language`
(`user_id`,`native`,`other`,`other_list`,`other_read`, `other_spokint`
,`other_spokprod`,`other_writ` )
VALUES
('$id','$native','$other','$other_list','$other_read','$other_spokint',
'$other_spokprod','$other_writ') ";
mysql_query($sql_insert,$link) or die("Insertion Failed:" . mysql_error());
}
header("Location: myaccount.php?id=' . $_SESSION[user_id] .'");
exit();
Would appreciate any help!
I think this is because your initial select query is selecting all users that are not banned
So need to change the query to filter by the new user:
"SELECT `id` FROM users WHERE `banned` = '0' and id=" . $_SESSION['$user_id'];
The reason why the user_id field kept getting populated as 1 was because mysql_fetch_row was getting the first record which was user id 1.
So if you filter it by the new user, mysql_fetch_row should get the id of the new user.
EDIT
I'm just looking at the code again, and it looks like you do not store the user id in php after you insert it, so your user_id for $_SESSION is null.
So my above example will not work. Instead of the above query, use the following function to get the id of your newly created user. You call this function after you run your insert query. That function will get the new of your newly created user.
mysql_insert_id()
http://php.net/manual/en/function.mysql-insert-id.php
EDIT 2
Ok, since mysql_insert_id() didn't work for you, maybe you can try the following. I just changed your select query to order by id desc.
$result = mysql_query("SELECT `id` FROM users WHERE `banned` = '0' order by id desc")
Just a note, this is probably not the best solution. But on a low traffic website it should be fine. To make the query a bit more accurate, you'd want to search for the user id based on a unique field like a username or email. This would make sure you get the correct id back.
EDIT 3
Here is an example of checking for the user's email. This is just the mysql query, you'll have to adjust this for php. Sorry I'm in class right now.
"SELECT `id` FROM users WHERE `banned` = '0' and email='user#email.com' limit 1
I'm working on a codeigniter project and I'm trying to troubleshoot a sql issue. I have a query that updates a date field in my table and it's not updating it at all.
I have this table
CREATE TABLE `Customer` (
`customer_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`first_name` varchar(55) NOT NULL DEFAULT '',
`last_name` varchar(55) NOT NULL DEFAULT '',
`city` varchar(255) DEFAULT '',
`state` char(2) DEFAULT '',
`zip` int(5) DEFAULT NULL,
`title` varchar(255) NOT NULL DEFAULT '',
`image` varchar(255) DEFAULT '',
`blurb` blob,
`end_date` date DEFAULT NULL,
`goal` int(11) DEFAULT NULL,
`paypal_acct_num` int(11) DEFAULT NULL,
`progress_bar` enum('full','half','none') DEFAULT NULL,
`page_views` int(11) NOT NULL DEFAULT '0',
`total_pages` int(11) NOT NULL DEFAULT '0',
`total_conversions` int(11) NOT NULL DEFAULT '0',
`total_given` int(11) NOT NULL DEFAULT '0',
`conversion_percentage` int(11) NOT NULL DEFAULT '0',
`avg_contribution` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`customer_id`)
) ENGINE=MyISAM AUTO_INCREMENT=15 DEFAULT CHARSET=utf8;
and when I run this query to insert data, it runs fine and sets the date to 2012-11-01
INSERT INTO `Customer` (`first_name`, `last_name`, `end_date`) VALUES ('John', 'Smith2', '2012-11-01');
Then I get the customer_id and try to run this query
UPDATE `Customer` SET `end_date` = '2012-14-01' WHERE `customer_id` = '18';
and it sets the date end_date field to 0000-00-00.
Why is it changing the end date to 0000-00-00 rather than 2012-14-01?
2012-14-01 is first day of fourteenth month :)
(so its invalid date, thus casted to 0000-00-00 and Data truncated for column 'end_date' at row 1 warning was returned by mysql, which you can see by querying SHOW WARNINGS to mysql immediately after badly behaving query)
2012-01-14 is 14th of January.
use this:
UPDATE `Customer` SET `end_date` = date('Y-m-d') WHERE `customer_id` = '18';
Use date function to update this field.