Dynamically Check and Create Table in MySQL - php

I'm having a problem creating a dynamic table in the database. If the table already exists in the database, then a new one should not be created.
if( mysqli_num_rows(mysqli_query("SHOW TABLES LIKE abc")) == 1){
echo "Already Exit";
} else {
//echo "not exit";
$sql="CREATE TABLE `decoration`.`newtable` (`id` INT NOT NULL AUTO_INCREMENT ,`company_id` VARCHAR( 20 ) NOT NULL ,`list_name` VARCHAR( 50 ) NOT NULL ,`created` INT NOT NULL ,`modified` INT NOT NULL ,`status` INT NOT NULL ,PRIMARY KEY ( `id` )) ENGINE = INNODB";
if ($con->mysqli_query($sql)){
echo "created";
} else {
echo "not created";
}
}

You can go with below query
CREATE TABLE IF NOT EXISTS `schema`.`Employee` (
`idEmployee` VARCHAR(45) NOT NULL ,
`Name` VARCHAR(255) NULL ,
`idAddresses` VARCHAR(45) NULL ,
PRIMARY KEY (`idEmployee`) ,
CONSTRAINT `fkEmployee_Addresses`
FOREIGN KEY `fkEmployee_Addresses` (`idAddresses`)
REFERENCES `schema`.`Addresses` (`idAddresses`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_bin
IF NOT EXISTS will check the table exists or not and if table exists in the database it will not create new one.
Ref : http://dev.mysql.com/doc/refman/5.7/en/create-table.html
Hope this will help!

Related

Insert Data into a table in php which has a foreign key field

I am modifiny an existing project by adding a feedback form to it. I need to store feedback form data into a table call feedback_formtb. I code the sql to create this table. And also there is an already created table call profile_request and I want to take a foreign key from this profile_request table. So I add the request_id field as the foreign key.(I have no permission to edit profile_request table because that part is already developed)
I crate a file call feedback_test.php.
Now I want to insert feedback form data to the feedback_formtb table. I have done it according to my understanding. But I am not sure whether this sql insert query is correct because of the foreign key and I is this correctly insert data to the table.(I have no user interfaces since i am asking to add this feed back form to the existing project).
Really appreciate your help if some one can help me to tell where this is ok. Thanks in advance.
===============feedback_formtb table create===================
DROP TABLE IF EXISTS `feedback_formtb`;
CREATE TABLE IF NOT EXISTS `feedback_formtb` (
`fid` int(10) NOT NULL,
`job_complete` tinyint(2) NOT NULL,
`satisfaction` double NOT NULL,
`reason` int(20) NOT NULL,
`comment` text NOT NULL,
`request_id` int(10) NOT NULL,
PRIMARY KEY (`fid`),
FOREIGN KEY (`request_id`) REFERENCES profile_requests(`id`)
)ENGINE=InnoDB DEFAULT CHARSET=latin1;
=============profile_requests Table=================
DROP TABLE IF EXISTS `profile_requests`;
CREATE TABLE IF NOT EXISTS `profile_requests` (
`updated_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
`created_at` timestamp NOT NULL DEFAULT current_timestamp(),
`created_by` int(10) UNSIGNED NOT NULL,
`updated_by` int(10) UNSIGNED NOT NULL,
`id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
`user_id` int(10) UNSIGNED NOT NULL,
`profile_id` int(10) UNSIGNED NOT NULL,
`expected_date` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`lat` float UNSIGNED NOT NULL,
`lng` float UNSIGNED NOT NULL,
`city_id` int(11) NOT NULL,
`message` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`state` tinyint(3) UNSIGNED NOT NULL DEFAULT 1 COMMENT '1:new request, 2:accepted,3:rejected',
`urgent` tinyint(3) UNSIGNED NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=69 DEFAULT CHARSET=latin1;
=================feedback_test.php=================
<?php
require_once 'auth.php';
// assigning values
$id = $_JSON['fid'] ?? NULL;
$request_id = $_JSON['$request_id'] ?? NULL;
$job_complete = $_JSON['job_complete'] ?? NULL;
$satisfaction = $_JSON['satisfaction'] ?? NULL;
$reason = $_JSON['reason'] ?? NULL;
$comment = $_JSON['comment'] ?? NULL;
$success = TRUE;
$submit = $_JSON['submit'] ?? NULL;
if ($submit !== NULL) { // if submit success
if ($job_complete === NULL) { // if job_complete fails
echo json_encode(['error' => 'job_complete not provided']);
die;
}else if ($satisfaction === NULL) { // if satisfaction fails
echo json_encode(['error' => 'satisfaction not provided']);
die;
}else if ($reason === NULL) { //if reason fails
echo json_encode(['error' => 'job_complete not provided']);
die;
}else if ($comment === NULL) { //if comment fails
echo json_encode(['error' => 'job_complete not provided']);
die;
}
// Insert Data
$ips = $mysqli->prepare('INSERT INTO feedback_formtb (job_complete, satisfaction, reason, comment, request_id) VALUES (?, ?, ?, ?, ( SELECT id FROM profile_requests WHERE id = ? ))');
$ips->bind_param('idisi', $job_complete, $satisfaction, $reason, $comment, $request_id);
if($ips->execute()){
$success = TRUE;
}if (!$ips->execute()) {
echo json_encode(['error' => 'Fail to submit']);
die;
}
}
?>
You don't need the subquery. Just use $request_id as the value of the column.
$ips = $mysqli->prepare('
INSERT INTO feedback_formtb (job_complete, satisfaction, reason, comment, request_id)
VALUES (?, ?, ?, ?, ?)');
The foreign key constraint will ensure that $request_id is valid. If you try to insert an ID that doesn't exist in profile_requests, this will get an error.

i want to create table with php variable + name

i want to create table with php variable+ name
like.
here is my code
if($conn->query($sql1)===TRUE){
$_SESSION['username'] = $x;
$sql = "CREATE TABLE $x
(
ID int NOT NULL AUTO_INCREMENT,
image blob,
date datetime,
status longtext,
PRIMARY KEY (ID)
)";
$sql2 = "CREATE TABLE ".$x."_frnd
(
ID int NOT NULL AUTO_INCREMENT,
myfrndname varchar(255),
myfrndusername varchar(255),
PRIMARY KEY (ID)
)";
$result= mysqli_query($conn,$sql,$sql2);
if ($conn->query($result) === TRUE) {
}
here ($x) is a variable and frnd is mannual name-
i want result table like this.
[ adminfrnd ].
please suggest me.
Try something like this:
CREATE TABLE IF NOT EXISTS `{$x}frnd` (
`id` mediumint(6) unsigned zerofill NOT NULL auto_increment,
`myfrndname` varchar(255) NOT NULL,
`myfrndlastname` varchar(255) NOT NULL,
`myfrndusername` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin
by the way
Why do you want to make own table for each admin ?
What you have to do is to append text like this:
$sql = "CREATE TABLE " . $x . "frnd
( ID int NOT NULL AUTO_INCREMENT,
myfrndname varchar(255),
myfrndlastname varchar(255),
myfrndusername varchar(255),
PRIMARY KEY (ID) )";
In your example $x should be string.
Your code will look like:
$x="admin";
$sql = "CREATE TABLE ".$x."_frnd
( ID int NOT NULL AUTO_INCREMENT,
myfrndname varchar(255),
myfrndlastname varchar(255),
myfrndusername varchar(255),
PRIMARY KEY (ID) )";
$result= mysqli_query($conn,$sql);
if ($conn->query($result) === TRUE) {
}
Note: its never good habit to use .(dot) in table name use _(underscore) instead

Trying to join certain values in different tables in mysql

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

message: successfully created tables but only the first one appears in database

I am trying to populate a database with tables (am new to this) The message I get back upon execution of .php is:
Table "users" successfully created
Table "tempRes" successfully created
Table "empRec" successfully created
However the second and third tables are not appearing in the database in phpMyAdmin. SHOW TABLES & SHOW TABLE STATUS only shows "user" table.
Does anyone know why this is happening? How can I rectify?
Here is my code:
<?php
// connect to the MySQL server
$conn = new mysqli('localhost', 'fiona', 'xxx', 'Org_db');
// check connection
if (mysqli_connect_errno()) {
exit('Connect failed: '. mysqli_connect_error());
}
// Performs the $sql query on the server to create the table users
$sql = "CREATE TABLE IF NOT EXISTS `users` (
`id` INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
`name` VARCHAR(25) NOT NULL,
`pass` VARCHAR(18) NOT NULL,
`email` VARCHAR(45),
`reg_date` TIMESTAMP
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8";
// performs query to check table successfully created or get error message
if ($conn->query($sql) === TRUE) {
echo '<br/>Table "users" successfully created<br/>';
}
else {
echo 'Error: '. $conn->error;
}
// Performs the $sql query on the server to create the table temporary reservations
"CREATE TABLE IF NOT EXISTS `tempRes` (
`tr_id` INT NOT NULL AUTO_INCREMENT,
`aaid` INT NOT NULL,
`cid` INT NOT NULL,
`date_res` DATE NOT NULL,
`rem` VARCHAR(5) NOT NULL,
primary key ( `tr_id` )) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8";
if ($conn->query($sql) === TRUE) {
echo 'Table "tempRes" successfully created<br/>';
}
else {
echo 'Error: '. $conn->error;
}
// Performs the $sql query on the server to create the table employee records
"CREATE TABLE IF NOT EXISTS `empRec` (
`eid` INT NOT NULL auto_increment,
`empPos` VARCHAR( 20 ) NOT NULL,
`tfn` INT NOT NULL,
`emp_DOB` DATE NOT NULL,
`eStart` DATE NOT NULL,
`super_co` VARCHAR( 30 ),
`s_mem_no` INT NOT NULL,
`icin` INT NOT NULL,
`epn` INT NOT NULL,
primary key ( emp_id )) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8";
if ($conn->query($sql) === TRUE) {
echo 'Table "empRec" successfully created<br/>';
}
else {
echo 'Error: '. $conn->error;
}
?>
Your not storing the second and third create statements in $sql variable. That's why isn't it?
Add $sql = infront of those two statements as well

set relation grocery crud error

I have 2 tables
CREATE TABLE `tbl_patient` (
id_patient INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(25) NOT NULL DEFAULT "not available",
att1 VARCHAR(5 ) NOT NULL DEFAULT "att1",
att2 VARCHAR(25) NOT NULL DEFAULT "att2",
att3 VARCHAR(25) NOT NULL DEFAULT "att3",
CONSTRAINT `uc_Info_patient` UNIQUE (`id_patient`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
and
CREATE TABLE `tbl_patient_medicine` (
id_patient_medicine INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
id_patient INTEGER NOT NULL,
name_medicine VARCHAR(50) NOT NULL DEFAULT "",
dosis VARCHAR(50) NOT NULL DEFAULT "",
start_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
treatment VARCHAR(50) NOT NULL DEFAULT "",
times_per_day VARCHAR(50) NOT NULL DEFAULT "",
CONSTRAINT fk_ID_Patient_Medicine FOREIGN KEY (id_patient) REFERENCES `tbl_patient`(id_patient)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
As you can see table patient_medicine is the intermediate table of between tbla_medicines, and table patient.
Now I want to consult all data from tbl_patient_medicine with grocery crud like in this sqlfiddle
supossing I pass the id in the uri (in the example will be id_patient=1)
I have
public function details_medication($my_id = 0)
{
try{
$crud = new grocery_CRUD();
$crud->where('id_patient',$my_id);
$crud->set_table('tbl_patient_medicine');
//HOW TO DO IT?
$crud->set_relation('id_patient', 'tbl_patient', 'id_patient');
$output = $crud->render();
$this->_output($output);
}catch(Exception $e){
show_error($e->getMessage().' --- '.$e->getTraceAsString());
}
}
SO I have tried different ways but got errors like this:
A Database Error Occurred
Error Number: 1052
Column 'id_patient' in where clause is ambiguous
SELECT `tbl_patient_medicine`.*, j7a675883.id_patient AS s7a675883
FROM (`tbl_patient_medicine`)
LEFT JOIN `tbl_patient` as j7a675883
ON `j7a675883`.`id_patient` = `tbl_patient_medicine`.`id_patient` WHERE `id_patient` = '1' LIMIT 25
Line Number: 87
I did your example:
Controller:
function medicine()
{
$crud = new grocery_CRUD();
$crud->set_table('tbl_patient_medicine');
$crud->required_fields('id_patient','name_medicine','dosis','start_date','treatment','time_per_day');
$crud->columns('id_patient','name_medicine','dosis','start_date','treatment','time_per_day');
$crud->fields('id_patient','name_medicine','dosis','start_date','treatment','time_per_day');
$crud->set_relation('id_patient','tbl_patient','name');
$output = $crud->render();
$this->_example_output($output);
}
It works!
Edited:
$crud->set_relation('id_patient','tbl_patient','{name}, {att1}, {att2}, {att3}');
Try by changing WHERE j7a675883.id_patient

Categories