i have a table tracker_item that looks like this
tracker_item
id heading trackerid
1 name 1
2 location 1
3 age 1
4 candidate 2
5 area 2
I wish to create different database table according to trackerid using the parameters that are below heading.
E.g acc to the above table tracker_item i want that 2 tables should get created
table1
id name location age
table 2
id candidate area
The code that i tried is
$sql="SELECT * FROM `tracker_item` where trackerid='".$trackerid."' ";
$result = mysqli_query($con, $sql);
if(mysqli_num_rows($result)>0)
{
while($row = mysqli_fetch_assoc($result))
{
echo $sql1 = "CREATE TABLE item (id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
".
$row['heading']
." VARCHAR(30) NOT NULL,
resume VARCHAR(50)
)";
}
if (mysqli_query($con, $sql1))
{
echo "Table created successfully";
}
else
{
echo "Error creating table: " . mysqli_error($con);
}
}
output for $sql1 that i got was
CREATE TABLE item (id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, name VARCHAR(30) NOT NULL, resume VARCHAR(50) )
CREATE TABLE item (id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, location VARCHAR(30) NOT NULL, resume VARCHAR(50) )
CREATE TABLE item (id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, age VARCHAR(30) NOT NULL, resume VARCHAR(50) )
Instead of multiple tables i would like to get o/p of $sql1 look like the following so that a table can be created in database
CREATE TABLE item ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, name VARCHAR(30) NOT NULL, location VARCHAR(30) NOT NULL, age VARCHAR(50) )
Can anyone please tell how it can be done
You just need to modify your while loop and do the CREATE before the loop. You only want the loop to add columns via concatenation:
if(mysqli_num_rows($result)>0)
{
$sql1 = "CREATE TABLE item (id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, ";
while($row = mysqli_fetch_assoc($result))
{
$sql1 .= $row['heading']." VARCHAR(30) NOT NULL, ";
}
$sql1 .= "resume VARCHAR(50)) ";
if (mysqli_query($con, $sql1))
{
echo "Table created successfully";
}
else
{
echo "Error creating table: " . mysqli_error($con);
}
}
Concatenate the entire query in this way and then execute the query.
Output:
CREATE TABLE item (id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, name VARCHAR(30) NOT NULL, location VARCHAR(30) NOT NULL, age VARCHAR(30) NOT NULL, candidate VARCHAR(30) NOT NULL, area VARCHAR(30) NOT NULL, resume VARCHAR(50))
I hate when people say "I'm not that far along..." or "This site will not be public..." or "It's only for school, so security doesn't matter...". If teachers and professors are not talking about security from day one, they're doing it wrong. Challenge them. They're teaching sloppy and dangerous coding practices which students will have to unlearn later. I also hate it when folks say, "I'll add security later..." or "Security isn't important now..." or "Ignore the security risk...". If you don't have time to do it right the first time, when will you find the time to add it later?
Related
I am creating a MySQL database and this doesn't seem to work, i was able to create a review table but now i'm trying to drop that table and create a reviews table but it doesn't seem to work. Please can someone take a look at this and help me check to see what's wrong here?
$reviewsTable = "CREATE TABLE reviews (
ID int NOT NULL AUTO_INCREMENT,
Name varchar(100) NOT NULL,
Website varchar(100) NOT NULL,
Review varchar(100) NOT NULL,
TimeOfYear varchar(50),
DayOfYear varchar(50),
PRIMARY KEY (website)
)";
$drop = "DROP TABLE review";
mysqli_query($connect,$drop);
mysqli_query($connect,$reviewsTable);
Just use if exists to drop the table if there is one then create your table.
Id has to be primary key because of the auto increment. all auto increments have to be primary key. You can index website though. but i set id as primary key below this should help.
$reviewsTable = "
DROP TABLE IF EXISTS review;
CREATE TABLE reviews (
ID int NOT NULL AUTO_INCREMENT,
Name varchar(100) NOT NULL,
Website varchar(100) NOT NULL,
Review varchar(100) NOT NULL,
TimeOfYear varchar(50),
DayOfYear varchar(50),
PRIMARY KEY (ID)
)";
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 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.
Please i need your help with my script. Whenever i include
AND maintable.semester_name = '$semester_name'
in the MySQL Query, it returns 0 for both values of semester_name, when actually
only one is supposed to have a value of 0 when echo $nums is processed. When i
remove
AND maintable.semester_name = '$semester_name'
the query gives normal results as i expect.
Thanks.
$query = "SELECT *
FROM maintable
WHERE maintable.matric_no = '$matric_no'
AND maintable.session = '$session'
AND maintable.semester_name = '$semester_name'
AND maintable.level = '$level'";
$result = mysql_query($query);
$nums = mysql_numrows($result);
echo $nums ;
TABLE STRUCTURE
COURSES
course_id int(100)
course_code varchar(100)
course_title varchar(100)
course_unit int(10)
MAINTABLE
maintable_id int(255)
matric_no int(10)
session varchar(10)
semester_name varchar(10)
course_code varchar(10)
level int(10)
score int(10)
grade varchar(4)
RESULT_UPLOAD
upload_id int(10)
session varchar(10)
semester_name varchar(10)
course_code varchar(10)
level varchar(10)
SEMESTER
semester_id int(10)
semester_name varchar(10)
STUDENT
matric_no int(10)
first_name varchar(100)
last_name varchar(100)
other_name varchar(100)
level int(10)
USERS
users_id int(10)
title varchar(20)
first_name varchar(20)
last_name varchar(20)
username varchar(20)
password varchar(100)
register_date datetime
tmp_name varchar(100)
type varchar(20)
name varchar(20)
size int(10)
YEAR
level_id int(10)
level int(10)
Your query is correct, but with bit of ambiguity. The following query is run as exactly you are doing, but with less words.
$query = "SELECT *
FROM maintable
WHERE matric_no = '$matric_no'
AND session = '$session'
AND semester_name = '$semester_name'
AND level = '$level'";
Now, about your problem, the only way this might be happening may be due to no record is matching the records in your database.
Try to get the query you are running with echo $query and run the query directly from phpmyadmin to see how many result set you will get.
The query is correct. I guess your conditions really don't match any rows in the table. Just check what values you have in the database and what your are passing into the conditions.
Try this query ...it works
$query = "SELECT *FROM maintable WHERE maintable.matric_no = '".$matric_no."'AND maintable.session = '".$session."' AND maintable.semester_name = '".$semester_name."' AND maintable.level = '".$level."' ";