I have this task from school, and I am confuse and lost on how I got to do this.
So basically I have to create 2 tables to the database but I have to created from php.
I have created the first table, but not the second one for some reason.
And then, I have to populate first and second tables with 10 and 20 sample records respectively, populate, does it mean like adding more fake users? if so is it like the code shown below?
*I got error on the populating second part as well
Thank you so much for the help.
<?php
$host = "host";
$user = "me";
$pswd = "password";
$dbnm = "db";
$conn = #mysqli_connect($host, $user, $pswd, $dbnm);
if (!$conn)
die ("<p>Couldn't connect to the server!<p>");
$selectData = #mysqli_select_db ($conn, $dbnm);
if(!$selectData)
{
die ("<p>Database Not Selected</p>");
}
//1st table
$sql = "CREATE TABLE IF NOT EXISTS `friends`
(
`friend_id` INT NOT NULL auto_increment,
`friend_email` VARCHAR(20) NOT NULL,
`password` VARCHAR(20) NOT NULL,
`profile_name` VARCHAR(30) NOT NULL,
`date_started` DATE NOT NULL,
`num_of_friends` INT unsigned,
PRIMARY KEY (`friend_id`)
)";
//2nd table
$sqlMyfriends = "CREATE TABLE `myfriends`
(
`friend_id1` INT NOT NULL,
`friend_id2` INT NOT NULL,
)";
$query_result1 = #mysqli_query($conn, $sql);
$query_result2 = #mysqli_query($conn, $sqlMyfriends);
//populating 1st table
$sqlSt3="INSERT INTO friends (friend_id, friend_email, password, profile_name, date_started, num_of_friends)
VALUES('NULL','email#email.com','123','abc','2012-10-25', 5)";
$queryResult3 = #mysqli_query($dbConnect,$sqlSt3)
//populating 2nd table
$sqlSt13="INSERT INTO myfriends VALUES(1,2)";
$queryResult13=#mysqli_query($dbConnect,$sqlSt13);
mysqli_close($conn);
?>
The others have addressed one of your issues, so this is in relation to not being able to add values to your tables (populate). Your connection link is $conn -
$conn = #mysqli_connect($host, $user, $pswd, $dbnm);
ie.
$query_result1 = #mysqli_query($conn, $sql);
but when you are adding your values to the tables, you changed your connection link to $dbConnect
...
$queryResult3 = #mysqli_query($dbConnect,$sqlSt3)
...
$queryResult13=#mysqli_query($dbConnect,$sqlSt13);
To insert multiple values into your table you could add a comma and additional parentheses ,() -
//populating 2nd table
$sqlSt13="INSERT INTO myfriends VALUES(1,2),(2,3),(3,1)";
$queryResult13=#mysqli_query($conn,$sqlSt13);
Or you could use mysqli_multi_query, and list each one-
//populating 2nd table
$sqlSt13 ="INSERT INTO myfriends VALUES (1,2);";
$sqlSt13 .="INSERT INTO myfriends VALUES (2,3);";
$sqlSt13 .="INSERT INTO myfriends VALUES (3,1);";
$queryResult13=#mysqli_query($conn,$sqlSt13);
see the manual for mysqli_multi_query - php.net/manual/en/mysqli.multi-query.php
You have an extra comma here that might cause an error:
friend_id2 INT NOT NULL,
should be:
$sqlMyfriends = "CREATE TABLE `myfriends` (
`friend_id1` INT NOT NULL,
`friend_id2` INT NOT NULL
)";
I wish I could be at school now :)
You have the following errors in code:
1) $queryResult3 = #mysqli_query($dbConnect,$sqlSt3)
Is correct: $queryResult3 = #mysqli_query($dbConnect,$sqlSt3);
2) $sqlMyfriends = "CREATE TABLE myfriends
(
friend_id1 INT NOT NULL,
friend_id2 INT NOT NULL,
)";
Is correct: $sqlMyfriends = "CREATE TABLE myfriends
(
friend_id1 INT NOT NULL,
friend_id2 INT NOT NULL)";
3) $queryResult3 = #mysqli_query($conn,$sqlSt3);
Is correct: $queryResult3 = mysqli_query($conn,$sqlSt3);
Code correct is:
Couldn't connect to the server!");
$selectData = #mysqli_select_db ($conn, $dbnm);
if(!$selectData)
{
die ("Database Not Selected");
}
//1st table
$sql = "CREATE TABLE IF NOT EXISTS `friends`
(
`friend_id` INT NOT NULL auto_increment,
`friend_email` VARCHAR(20) NOT NULL,
`password` VARCHAR(20) NOT NULL,
`profile_name` VARCHAR(30) NOT NULL,
`date_started` DATE NOT NULL,
`num_of_friends` INT unsigned,
PRIMARY KEY (`friend_id`)
)";
//2nd table
$sqlMyfriends = "CREATE TABLE `myfriends`
(
`friend_id1` INT NOT NULL,
`friend_id2` INT NOT NULL
)";
$query_result1 = #mysqli_query($conn, $sql);
$query_result2 = #mysqli_query($conn, $sqlMyfriends);
//populating 1st table
$sqlSt3="INSERT INTO friends (friend_id, friend_email, password, profile_name, date_started, num_of_friends)
VALUES('NULL','email#email.com','123','abc','2012-10-25', 5)";
$queryResult3 = mysqli_query($conn,$sqlSt3);
//populating 2nd table
$sqlSt13="INSERT INTO myfriends VALUES(1,2)";
$queryResult13=#mysqli_query($dbConnect,$sqlSt13);
mysqli_close($conn);
?>
I hope to help !
Related
I'm a newbie in PHP. I hope someone can help me. before that sorry my english's bad.
I want set kd_transaksi base on date and id from another table. when people booking, system automatically set kd_transaksi.
$tgl_pesan = date("Ymd");
$cek = mysqli_query($conn, "SELECT max(kd_booking) AS kode FROM booking WHERE kd_booking LIKE '$tgl_pesan%'");
$row = mysqli_fetch_array($cek);
$kdMax = $row['kode'];
$nourut = substr($kdMax, 8, 4);
$nourut++;
$char = "BO";
$kd_transaksi = $char.$tgl_pesan.printf('%04s', $nourut);
$kd_booking = mysqli_insert_id($conn);
$book = "INSERT INTO detail_booking (kd_booking,kd_transaksi,total_bayar) VALUES ('".$kd_booking."','$kd_transaksi',$total_bayar')";
$ok = mysqli_query($conn,$book);
if ($ok) {
header('location:../mybooking.php');
} else{
mysqli_close($conn);
}
but result in query $cek is NULL.
$cek = mysqli_query($conn, "SELECT max(kd_booking) AS kode FROM booking WHERE kd_booking LIKE '$tgl_pesan%'");
how do I fix it?
booking table
CREATE TABLE `booking` (
`kd_booking` int(11) NOT NULL,
`id_user` int(11) NOT NULL,
`kd_paket` int(11) NOT NULL,
`jml_org` int(11) NOT NULL,
`tgl_pesan` date NOT NULL,
`tgl_wisata` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
What i want is
If someone booking today and get kd_booking 21, then the output would be : BO2018120521.
First of all, you have something wrong with your CREATE TABLE. When you create a table you should have an AUTOINCREMENT primary key, this is your id. So it would be something like this:
CREATE TABLE `booking` ( `id` INT NOT NULL AUTO_INCREMENT , `id_user` INT(11) NOT NULL , `kd_paket` INT(11) NOT NULL , `jml_org` INT(11) NOT NULL , `tgl_wisata` DATE NOT NULL , `tgl_pesan` DATE NOT NULL , PRIMARY KEY (`id`)) ENGINE = InnoDB;
As i can se you have two errors:
Date should be like date('Y-m-d') http://php.net/manual/en/function.date.php
You're trying to insert an int value like '".$kd_booking."' when that just works for strings.
Hope it helped.
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;
}
Currently I want to get data from another table with my foreign key.
I have already setup my foreign key.
I have tables setup like this:
CREATE TABLE IF NOT EXISTS `album` (
`album_ID` int(11) NOT NULL AUTO_INCREMENT,
`album_navn` varchar(150) NOT NULL,
PRIMARY KEY (`album_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;
--
--
INSERT INTO `album` (`album_ID`, `album_navn`) VALUES
(1, 'Nytår'),
(2, 'Berlin'),
(3, 'Færøerne'),
(5, 'TEST');
CREATE TABLE IF NOT EXISTS `billeder` (
`billeder_ID` int(11) NOT NULL AUTO_INCREMENT,
`billeder_navn` varchar(150) NOT NULL,
`billeder_fotograf` varchar(150) NOT NULL,
`billeder_sti` varchar(150) NOT NULL,
`fk_album_ID` int(11) NOT NULL,
PRIMARY KEY (`billeder_ID`),
KEY `fk_album_ID` (`fk_album_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=54 ;
--
--
INSERT INTO `billeder` (`billeder_ID`, `billeder_navn`, `billeder_fotograf`, `billeder_sti`, `fk_album_ID`) VALUES
(24, 'Vi tester4', 'Nytår', 'full_nytaar.jpg', 1),
(25, '', 'Nytår', 'full_nytaar2.jpg', 1),
(26, '', 'Nytår', 'full_nytaar4.jpg', 1),
Where I want to get ALBUM_NAVN via my fk_album_ID
so it will be possible to get it like this:
$row[album_navn]
I have tried to do it, but im lost.
Thanks in advance.
Regards, Kristian
Please try this query
SELECT * FROM billeder LEFT JOIN album ON billeder.fk_album_ID = album.album_ID
Try:
select * from billeder left join album where billeder.fk_album_ID=album.album_ID
This query will bring the desired result.
SELECT b . * , a.album_navn FROM `billeder` b, album a WHERE b.fk_album_ID = a.album_ID
Please try this php code as well. This is working and tested. You need to use join in query.
// CONNECT TO THE DATABASE
$DB_NAME = 'test';
$DB_HOST = 'localhost';
$DB_USER = 'root';
$DB_PASS = '';
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//query
$query = " SELECT b . * , a.album_navn FROM `billeder` b, album a
WHERE b.fk_album_ID = a.album_ID";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
// show data
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo ($row['album_navn']);
}
}
else {
echo 'No record found';
}
//close conn
mysqli_close($mysqli);
So I have this script just to create a table in my database. I've copied it over from an old script I did that is working right now. How come this one is not working? Anyone?
The error I am getting is "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 "'= varchar (20) NOT NULL, column_two = int NOT NULL auto_increment, column_thre' at line 2"
<?php
include("server_connect.php");
mysql_select_db("assignment5");
$create = "CREATE TABLE tbltable (
column_one = varchar (20) NOT NULL,
column_two = int NOT NULL auto_increment,
column_three = int NOT NULL,
column_four = varchar (15) NOT NULL,
column_five = year,
PRIMARY KEY = (column_one)
)";
$results = mysql_query($create) or die (mysql_error());
echo "The tables have been created";
?>
Remove all = as already suggested:
$create = "CREATE TABLE tbltable (
column_one varchar (20) NOT NULL,
column_two int NOT NULL auto_increment PRIMARY KEY,
column_three int NOT NULL,
column_four varchar (15) NOT NULL,
column_five year
)";
Each and every table should have a primary key and you must specify AUTO_INCREMENT column as PRIMARY KEY. In this case, the AUTO_INCREMENT column is column_two and I've set that as the PRIMARY KEY.
MySQLi Procedural
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// sql to create table
$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";
if (mysqli_query($conn, $sql)) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
(PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// sql to create table
$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";
// use exec() because no results are returned
$conn->exec($sql);
echo "Table MyGuests created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
The solution is to assign all the privileges to the BD user, like this:
GRANT ALL PRIVILEGES ON *. * TO 'user_name' # 'localhost';
Is it true that after a user signs up, a sql table is create for him to store his posts ?
I make it similar in mysql after the man insert him into my page. The database is the same name with but the table name is made when he log in first time.
class Users
{
var $username="root";
var $password="pass";
var $database="InsertIntoStackOverflow";
var $table_name="";
public function Users($username)
{
$table_name=$username."_tb";
echo $table_name."<br/>";
mysql_connect(localhost,$username, $password) or die("unable to connect to database ".mysql_error());
echo $database."<br/>";
mysql_selectdb($database) or die("unable to select db ".mysql_error());
$query="CREATE TABLE ".$table_name." (id tinyint(4) NOT NULL AUTO_INCREMENT, title VARCHAR(128) NOT NULL, date_post VARCHAR(100), date_edit VARCHAR(100), post_content TEXT NOT NULL)";
mysql_query($query) or die("Unable to create table. ".mysql_error());
}
}
But it display only table_name and an error, the database name not display. Error is NO DATABASE IS SELECTED/
EDIT
This class is call after he sign up
I also have a function postApost but when I do
ob_start();
session_start();
require("Users_DB.php");
$name=$_SESSION['user'];
echo 'Welcome '.$name;
$username=new UserDB($name);
there is no table created
Two variables with same name $username. Use $this for accessing variable of class. Missing quote(") with localhost - it must be string type parameter. and this code can't create table on Database because you use AUTO_INCREMENT on your code but forgot to mention that as a PRIMARY KEY. I think the following code help you a lot.
class Users
{
var $username="root";
var $password="pass";
var $database="InsertIntoStackOverflow";
var $table_name="";
function __construct($user_name)
{
$this->table_name=$user_name."_tb";
echo $this->table_name."<br/>";
mysql_connect("localhost",$this->username, $this->password) or die("unable to connect to database ".mysql_error());
echo $this->database."<br/>";
mysql_selectdb($this->database) or die("unable to select db ".mysql_error());
$query="CREATE TABLE ".$this->table_name." (id tinyint(4) NOT NULL AUTO_INCREMENT, title VARCHAR(128) NOT NULL, date_post VARCHAR(100), date_edit VARCHAR(100), post_content TEXT NOT NULL, PRIMARY KEY (id))";
mysql_query($query) or die("Unable to create table. ".mysql_error());
}
}
And you can use this class by the following way :
$clsName = new Users('username');
Create one table:
CREATE TABLE Posts (
id TINYINT(4) NOT NULL AUTO_INCREMENT,
user VARCHAR(20) NOT NULL,
title VARCHAR(128) NOT NULL,
date_post DATETIME,
date_edit DATETIME,
post_content TEXT NOT NULL
)
Inserting new posts:
$insert = "
INSERT INTO Posts (
user,
title,
date_post,
date_edit,
post_content
) VALUES (
'$username',
'$title',
NOW(),
NOW(),
'$post_content'
)
";
Updating is simple:
$update = "
UPDATE Posts SET
title = '$title',
post_content = '$post_content',
date_edit = NOW()
WHERE id = '$postid';
";
Get all posts for user:
$posts = "
SELECT title, date_post, date_edit, post_content
FROM Posts
WHERE user = '$username'
ORDER BY date_post
";