I am having trouble with my create a table .php script, It creates all tables in the database except one which is 'useroptions'. I am new to php but still understand it to an extent, feedback and help would be greatly appreciated.
<?php
include_once("php_includes/db_connect.php");
$tbl_users = "CREATE TABLE IF NOT EXISTS users (
id INT(11) NOT NULL AUTO_INCREMENT,
firstname VARCHAR(100) NOT NULL,
lastname VARCHAR(100) NOT NULL,
email VARCHAR(255) NOT NULL,
password VARCHAR(255) NOT NULL,
gender ENUM('m','f') NOT NULL,
avatar VARCHAR(255) NULL,
ip VARCHAR(255) NOT NULL,
signup DATETIME NOT NULL,
lastlogin DATETIME NOT NULL,
notescheck DATETIME NOT NULL,
activated ENUM('0','1') NOT NULL DEFAULT '0',
PRIMARY KEY (id),
UNIQUE KEY email (email)
)";
$query = mysqli_query($db_connect, $tbl_users);
if ($query === TRUE) {
echo "<h3>user table created OK :) </h3>";
} else {
echo "<h3>user table NOT created :( </h3>";
}
////////////////////////////////////
$tbl_useroptions = "CREATE TABLE IF NOT EXISTS useroptions (
id INT(11) NOT NULL,
question VARCHAR(255) NULL,
answer VARCHAR(255) NULL,
PRIMARY KEY (id),
UNIQUE KEY email (email)
)";
$query = mysqli_query($db_connect, $tbl_useroptions);
if ($query === TRUE) {
echo "<h3>useroptions table created OK :) </h3>";
} else {
echo "<h3>useroptions table NOT created :( </h3>";
}
////////////////////////////////////
$tbl_friends = "CREATE TABLE IF NOT EXISTS friends (
id INT(11) NOT NULL AUTO_INCREMENT,
user1 VARCHAR(100) NOT NULL,
user2 VARCHAR(100) NOT NULL,
datemade DATETIME NOT NULL,
accepted ENUM('0','1') NOT NULL DEFAULT '0',
PRIMARY KEY (id)
)";
$query = mysqli_query($db_connect, $tbl_friends);
if ($query === TRUE) {
echo "<h3>friends table created OK :) </h3>";
} else {
echo "<h3>friends table NOT created :( </h3>";
}
////////////////////////////////////
$tbl_blockedusers = "CREATE TABLE IF NOT EXISTS blockedusers (
id INT(11) NOT NULL AUTO_INCREMENT,
blocker VARCHAR(100) NOT NULL,
blockee VARCHAR(100) NOT NULL,
blockdate DATETIME NOT NULL,
PRIMARY KEY (id)
)";
$query = mysqli_query($db_connect, $tbl_blockedusers);
if ($query === TRUE) {
echo "<h3>blockedusers table created OK :) </h3>";
} else {
echo "<h3>blockedusers table NOT created :( </h3>";
}
////////////////////////////////////
$tbl_status = "CREATE TABLE IF NOT EXISTS status (
id INT(11) NOT NULL AUTO_INCREMENT,
osid INT(11) NOT NULL,
account_name VARCHAR(100) NOT NULL,
author VARCHAR(100) NOT NULL,
data TEXT NOT NULL,
postdate DATETIME NOT NULL,
PRIMARY KEY (id)
)";
$query = mysqli_query($db_connect, $tbl_status);
if ($query === TRUE) {
echo "<h3>status table created OK :) </h3>";
} else {
echo "<h3>status table NOT created :( </h3>";
}
////////////////////////////////////
$tbl_photos = "CREATE TABLE IF NOT EXISTS photos (
id INT(11) NOT NULL AUTO_INCREMENT,
user VARCHAR(100) NOT NULL,
gallery VARCHAR(16) NOT NULL,
filename VARCHAR(255) NOT NULL,
description VARCHAR(255) NULL,
uploaddate DATETIME NOT NULL,
PRIMARY KEY (id)
)";
$query = mysqli_query($db_connect, $tbl_photos);
if ($query === TRUE) {
echo "<h3>photos table created OK :) </h3>";
} else {
echo "<h3>photos table NOT created :( </h3>";
}
////////////////////////////////////
$tbl_notifications = "CREATE TABLE IF NOT EXISTS notifications (
id INT(11) NOT NULL AUTO_INCREMENT,
firstname VARCHAR(100) NOT NULL,
initiator VARCHAR(100) NOT NULL,
app VARCHAR(255) NOT NULL,
note VARCHAR(255) NOT NULL,
did_read ENUM('0','1') NOT NULL DEFAULT '0',
date_time DATETIME NOT NULL,
PRIMARY KEY (id)
)";
$query = mysqli_query($db_connect, $tbl_notifications);
if ($query === TRUE) {
echo "<h3>notifications table created OK :) </h3>";
} else {
echo "<h3>notifications table NOT created :( </h3>";
}
?>
Also I'm getting this error when I click on database ?
Error
SQL query:
SELECT tracking_active
FROM `phpmyadmin`.`pma_tracking`
WHERE db_name = 'circle'
AND table_name = 'blockedusers'
ORDER BY version DESC
MySQL said:
1146 - Table 'phpmyadmin.pma_tracking' doesn't exist
Your useroptions create table statement has an invalid unique key ref: UNIQUE KEY email (email). There is no column email on useroptions. Remove it and it will likely run clean.
As for the query issue, not really sure what you're trying to do.
Related
I am trying to create a "setup script" for my website. I would like to create the database, adding tables and some content at the same time. So far this is how I did it, but it seems kind off messy using multiple queries:
<?php
$servername = "localhost";
$username = "root";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Create database
$sql = "CREATE DATABASE MYDB";
if ($conn->query($sql) === TRUE) {
echo "1. Database created successfully <br/>";
$conn->select_db("MYDB");
$sql_members = "CREATE TABLE MEMBERS (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
USERNAME VARCHAR(30) NOT NULL,
EMAIL VARCHAR(40) NOT NULL,
DISCOUNT VARCHAR(5),
PASSW CHAR(128),
ROLE VARCHAR(9)
)";
if ($conn->query($sql_members) === TRUE) {
echo "2. Table MEMBERS created successfully <br/>";
} else {
echo "Error creating table: " . $conn->error;
}
$sql_content = "CREATE TABLE CONTENT (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
TITLE VARCHAR(30) NOT NULL,
TEXT VARCHAR(30) NOT NULL
)";
if ($conn->query($sql_content) === TRUE) {
echo "3. Table CONTENT created successfully <br/>";
} else {
echo "Error creating table: " . $conn->error;
}
} else {
echo "Error creating database: " . $conn->error;
}
$conn->close();
?>
Is there a better way?
Thanks!
== UPDATE ==
I have tried to export the database and use the resulted .sql file as my setup query, but something is wrong, I get:
Error creating tables: 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 CONTACTS (ID, NAME, PHONE,
EMAIL, ADDRESS, CITY, `COUN' at line 12
CREATE TABLE IF NOT EXISTS `CONTACTS` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`NAME` varchar(25) COLLATE utf8_romanian_ci NOT NULL,
`PHONE` varchar(16) COLLATE utf8_romanian_ci NOT NULL,
`EMAIL` varchar(35) COLLATE utf8_romanian_ci NOT NULL,
`ADDRESS` text COLLATE utf8_romanian_ci NOT NULL,
`CITY` varchar(16) COLLATE utf8_romanian_ci NOT NULL,
`COUNTRY` varchar(16) COLLATE utf8_romanian_ci NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_romanian_ci AUTO_INCREMENT=2 ;
INSERT INTO `CONTACTS` (`ID`, `NAME`, `PHONE`, `EMAIL`, `ADDRESS`, `CITY`, `COUNTRY`) VALUES
(1, 'Peter Brown', '0742062307', 'office#shop.com', 'Avenue 13.', 'Santaclaus', 'Austria');
== SOLUTUION ==
I needed "multi_query()" for executing my multiple queries.
You can try this too :p
$errors = [];
$table1 = "CREATE TABLE MEMBERS (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
USERNAME VARCHAR(30) NOT NULL,
EMAIL VARCHAR(40) NOT NULL,
DISCOUNT VARCHAR(5),
PASSW CHAR(128),
ROLE VARCHAR(9)
)";
$table2 = "CREATE TABLE CONTENT (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
TITLE VARCHAR(30) NOT NULL,
TEXT VARCHAR(30) NOT NULL
)";
$tables = [$table1, $table2];
foreach($tables as $k => $sql){
$query = #$conn->query($sql);
if(!$query)
$errors[] = "Table $k : Creation failed ($conn->error)";
else
$errors[] = "Table $k : Creation done";
}
foreach($errors as $msg) {
echo "$msg <br>";
}
You could export the whole database including all tables using the command line or using PhPMyAdmin. Then query the content of the file in php to create the database.
you can create a file and put all your sql queries in it..
CREATE TABLE MEMBERS (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
USERNAME VARCHAR(30) NOT NULL,
EMAIL VARCHAR(40) NOT NULL,
DISCOUNT VARCHAR(5),
PASSW CHAR(128),
ROLE VARCHAR(9)
);
CREATE TABLE CONTENT (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
TITLE VARCHAR(30) NOT NULL,
TEXT VARCHAR(30) NOT NULL
);
then in your php code:
$query = file_get_contents ('queries.sql');
if ($conn->query($query) === TRUE) {
echo "all tables created successfully <br/>";
} else {
echo "Error creating tables: " . $conn->error;
}
I did this earlier and it worked just fine and I even brought in another table and it was created just fine. I am stuck.
Here is the table that is not working.
<?php
include_once('dbconx.php');
$tbl_pages = "CREATE TABLE IF NOT EXISTS pages (
id INT(11) NOT NULL AUTO_INCREMENT,
label VARCHAR(20) NOT NULL,
title VARCHAR(50) NOT NULL,
body TEXT NOT NULL,
slug VARCHAR(50) NOT NULL,
create TIMESTAMP NOT NULL,
updated TIMESTAMP NULL,
PRIMARY KEY(id),
)";
$query = mysqli_query($dbcon, $tbl_pages);
if ($query === TRUE) {
echo "<h3>Pages table created OK :) </h3>";
} else {
echo "<h3>Pages table NOT created :( </h3>";
}
?>
One of your field names is a MySQL reserved words create. Try changing the field name to something like created. See MySQL Keywords and Reserved Words
You also have an extra comma after the primary key definition.
Try this query:
$tbl_pages = "CREATE TABLE IF NOT EXISTS pages (
id INT(11) NOT NULL AUTO_INCREMENT,
label VARCHAR(20) NOT NULL,
title VARCHAR(50) NOT NULL,
body TEXT NOT NULL,
slug VARCHAR(50) NOT NULL,
created TIMESTAMP NOT NULL,
updated TIMESTAMP NULL,
PRIMARY KEY(id)
)";
You can also echo mysqli_error if it fails so you can see details of the error.
I have below code I am trying to run..Connection is successfully created but still mysqli_query does not create a table.What I am missing...
here is the script I am executing...
error_reporting(E_ALL);
ini_set('display_errors', '1');
$con=mysqli_connect("localhost","xxxxxx","xxxxx","xxx");
if (mysqli_connect_errno()) {
echo mysqli_connect_error();
exit();
} else {
echo "Successful database connection";
}
$tbl_users = "CREATE TABLE IF NOT EXISTS users (
id INT(11) NOT NULL AUTO_INCREMENT,
firstname VARCHAR(255) NOT NULL,
lastname VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL,
password VARCHAR(255) NOT NULL,
gender ENUM('m','f') NULL,
state VARCHAR(255) NULL,
country VARCHAR(255) NULL,
userlevel ENUM('admin','user') NOT NULL DEFAULT 'user',
ip VARCHAR(255) NOT NULL,
signup DATETIME NOT NULL,
lastlogin DATETIME NOT NULL,
activated ENUM('0','1') NOT NULL DEFAULT '0',
PRIMARY KEY (email)
)";
$query = mysqli_query($con, $tbl_users);
if ($query === TRUE) {
echo "<h3>user table created OK :) </h3>";
} else {
echo "<h3>user table NOT created :( </h3>";
}
You need to change your Primary key to the auto_increment column, remove it from email, you can set this (email) to unique if it should be
CREATE TABLE IF NOT EXISTS users (
id INT(11) NOT NULL // >>> PRIMARY KEY //<<< AUTO_INCREMENT,
firstname VARCHAR(255) NOT NULL,
[Err] 1075 - Incorrect table definition; there can be only one auto column and it must be defined as a key
PRIMARY KEY (email) is the issue. Make id your primary key.
i'm very new to mysql and I am trying to create a database that can store users emails and passwords on one table and the values they input on another table, how do I join the tables to make sure that the inputted values are linked to the correct user. This is the code I've been using but it won't allow the value to be stored while the foreign key is run, but if I remove the foreign key I can store the value. Please help.
CREATE TABLE IF NOT EXISTS `data` (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`email` varchar(51) NOT NULL,
`password` varchar(15) NOT NULL,
PRIMARY KEY (`user_id`),
UNIQUE KEY `email_UNIQUE` (`email`)
)
CREATE TABLE IF NOT EXISTS `gluco` (
`G_id` int(11) NOT NULL AUTO_INCREMENT,
`bloods` decimal(4,2) NOT NULL,
`time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`user_id` int(11) NOT NULL,
FOREIGN KEY (`user_id`) REFERENCES `data`(`use_id`),
UNIQUE KEY `G_id_UNIQUE` (`G_id`)
)
<?php
include('db.php');
if (!isset($_POST['reading'])) { //checking if user has entered this page directly
include('contactus.php');
} else {
if (isset($_POST['reading'])&&$_POST['reading']==""||!isset($_POST['reading'])) {
$error[] = "fill in your blood/glucose";
}
$reading = mysql_real_escape_string($_POST['reading']);
$sql = "SELECT * FROM gluco WHERE bloods = '$reading'";
if(isset($error)){
if(is_array($error)){
echo "<div class=\"error\"><span>please check the errors and refill the form<span><br/>";
foreach ($error as $ers) {
echo "<span>".$ers."</span><br/>";
}
echo "</div>";
include('contactus.php');
}
}
if(!isset($error)){
$sreading=mysql_real_escape_string($_POST['reading']);
$sip=mysql_real_escape_string($_SERVER['HTTP_HOST']);
$save = mysql_query("INSERT INTO `gluco` ( `bloods` )VALUES ('$sreading')");
if($save){
echo "<div class=\"success\"><span>Your reading has been successfully stored</span><br/></div>";
} else {
echo "<div class=\"warning\"><span>Some Error occured during processing your data</div>";
}
}
}
?>
your code is correct in its logic. But theres an error on the referenced column name:
CREATE TABLE IF NOT EXISTS `data` (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`email` varchar(51) NOT NULL,
`password` varchar(15) NOT NULL,
PRIMARY KEY (`user_id`),
UNIQUE KEY `email_UNIQUE` (`email`)
)
CREATE TABLE IF NOT EXISTS `gluco` (
`G_id` int(11) NOT NULL AUTO_INCREMENT,
`bloods` decimal(4,2) NOT NULL,
`time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`user_id` int(11) NOT NULL,
FOREIGN KEY (`user_id`) REFERENCES `data`(`user_id`),
UNIQUE KEY `G_id_UNIQUE` (`G_id`)
)
and on this line:
$save = mysql_query("INSERT INTO `gluco` ( `bloods` )VALUES ('$sreading')");
you are not setting the user_id in your insert statement, so, the foreign key will not work and the insert will not be made. So, you'll need to have the user id stored in a variable (since i don't know the context and the scope in the code, i can't help you setting this variable). So, your code should be like that:
$save = mysql_query("INSERT INTO gluco (bloods, user_id)VALUES ('$sreading', $user_id)");
If I register a user using this table:
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;
and then once logged in to 'myaccount.php' use this code to enter values into another table, the language table:
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' order by id desc");
list($id) = mysql_fetch_row($result);
session_start();
$_SESSION['user_id'] = $id;
foreach ($_POST as $key => $value) if (empty($err)) {
for ($i = 0;$i < count($_POST["other"]);$i++) {
$native = mysql_real_escape_string($_POST['native'][$i]);
$other = mysql_real_escape_string($_POST['other'][$i]);
$other_list = mysql_real_escape_string($_POST['other_list'][$i]);
$other_read = mysql_real_escape_string($_POST['other_read'][$i]);
$other_spokint = mysql_real_escape_string($_POST['other_spokint'][$i]);
$other_spokprod = mysql_real_escape_string($_POST['other_spokprod'][$i]);
$other_writ = mysql_real_escape_string($_POST['other_writ'][$i]);
$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();
}
}
}
All is fine until , for example I register id=3 (in users table) and then log back into id=1 and change their details in the language table, then their user_id in the language table (which is foreign key to id in users table) is 3 when it should be 1. To make things simple, the id in users table should be same as the user_id in the language table. But when going back and changing data in the languages table the user_id stays the same as the last id that registered!
Please help!
This query you have:
$result = mysql_query("SELECT `id` FROM users WHERE `banned` = '0' order by id desc");
What is the purpose of it? You are assigning to $id the first value it finds, yet the query doesn't look for user name or anything else. You probably want to user $_SESSION['$user_id'] instead of $id as your user's ID.