Trying to join certain values in different tables in mysql - php

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

Related

Save and update with uniqid in database

I tried to insert the player with a unique id in the database.
This model works for me, but if I give it a key update it duplicates it in my database.
Option 1
$id = uniqid();
$insert_player_query = mysqli_query($db,"INSERT INTO players (id,nickname,score,time_online,mapname,sid) VALUES ('$id','$player_nickname','$player_score','$player_time','$mapname','$server_id') ON DUPLICATE KEY UPDATE score = score + VALUES(score), time_online = time_online + VALUES(time_online) WHERE id='$id'");
Option 2
Then I tried that, but it doesn't insert anything at all
$id = uniqid();
$sql=mysqli_query($db, "SELECT * FROM players WHERE nickname='$player_nickname'");
if (mysqli_num_rows($sql) > 0)
{
$insert_player_query2 = mysqli_query($db,"UPDATE players (nickname,score,time_online,mapname,sid) VALUES ($player_nickname','$player_score','$player_time','$mapname','$server_id') WHERE id='$id'");
} else {
$insert_player_query = mysqli_query($db,"INSERT INTO players (id,nickname,score,time_online,mapname,sid) VALUES ('$id','$player_nickname','$player_score','$player_time','$mapname','$server_id') WHERE id='$id'");
}
Remove "where" condition. It does not make any sense in "INSERT" statement.
You should check field and use:
CREATE TABLE `players` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`nickname` varchar(100) DEFAULT NULL,
`score` int(11) DEFAULT NULL,
`time_online` varchar(100) DEFAULT NULL,
`mapname` varchar(100) DEFAULT NULL,
`sid` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uniq` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
INSERT INTO players (id,nickname,score,time_online,mapname,sid) VALUES ('1','player_nickname','1','1','mapname','1')
ON DUPLICATE KEY UPDATE score = score + VALUES(score), time_online = time_online + VALUES(time_online)
Please try it.

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.

Cannot add or update a child row: a foreign key constraint fails (Mysql and Foreign key)

When I trying to run the code, this error shows up
Cannot add or update a child row: a foreign key constraint fails
(hotel_info.results, CONSTRAINT results_ibfk_5 FOREIGN KEY
(CustomerID) REFERENCES customer (CustomerID) ON DELETE CASCADE
ON UPDATE CASCADE)
Here is the code
$result = mysql_query("select customer.CustomerID from customer inner join results on customer.CustomerID = results.CustomerID where customer.Username = '".$aid."'");
if (false === $result)
{
echo mysql_error();
}
if (isset($_POST["submitbtn"]))
{
$LP = $_POST["LP"];
$budget = $_POST["budget"];
$checkin = $_POST["CheckIn"];
$checkout = $_POST["CheckOut"];
$unit = $_POST["unit"];
$smokep = $_POST["SmokeP"];
$spreq = $_POST["sp_req"];
if($checkin>$checkout)
{
?>
<script type="text/javascript">
alert("End Date must greater than Start Date.");
</script>
<?php
}
else
{
$query = mysql_query("INSERT INTO results(`LP`, `budget`, `CheckIn`, `CheckOut`, `unit`, `SmokeP`, `sp_req`, `CustomerID`) values ('$LP', '$budget',
'$checkin', '$checkout', '$unit', '$smokep', '$spreq', '$result')");
if (false === $query)
{
echo mysql_error();
}
echo "Reservation form has been submitted!<br>
<a href=view.php>view all</a>";
}
}
Here is the sql
CREATE TABLE IF NOT EXISTS `results` (
`BookID` int(10) NOT NULL AUTO_INCREMENT,
`LP` varchar(50) DEFAULT NULL,
`budget` varchar(50) DEFAULT NULL,
`CheckIn` varchar(50) DEFAULT NULL,
`CheckOut` varchar(50) DEFAULT NULL,
`unit` int(50) DEFAULT NULL,
`SmokeP` varchar(50) DEFAULT NULL,
`sp_req` varchar(255) DEFAULT NULL,
`CustomerID` int(10) NOT NULL,
PRIMARY KEY (`BookID`),
KEY `Username` (`CustomerID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=48 ;
CREATE TABLE IF NOT EXISTS `customer` (
`CustomerID` int(10) NOT NULL AUTO_INCREMENT,
`Username` varchar(50) NOT NULL,
`Password` varchar(50) NOT NULL,
`Email` varchar(50) NOT NULL,
`ContactNo` int(10) NOT NULL,
PRIMARY KEY (`CustomerID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
I've already stuck for two days because of this error, please help.
from the error it is clear that foreign key constraint fails. Please check your customer table which must have CustomerID that you are trying to insert in results table insert query i.e. check value of $id. have you assigned any value for $id
$query = mysql_query("INSERT INTO results(`LP`, `budget`, `CheckIn`, `CheckOut`, `unit`, `SmokeP`, `sp_req`, `CustomerID`) values ('$LP', '$budget',
'$checkin', '$checkout', '$unit', '$smokep', '$spreq', '$id')");
In above query value for $id not set so first assign value to that.

Not able to run create sql command with mysqli_query php

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.

It is not inserting data into a Table

I have some php code below that adds data into 2 tables, one known as the "Image Table" and another known as the "Image_Question" Table. The problem I'm facing is while it inserts into the "Image" Table, it doesn't insert any data into the "Image_Question" Table.
Now I know the PHP code is fine because it used to be able to insert the data into both tables with no problems.
Only after I added indexes and foreign keys to my table this problem started occurring.
Below is the PHP code that inserts the data into both tables:
move_uploaded_file($_FILES["fileImage"]["tmp_name"],"ImageFiles/" . $_FILES["fileImage"]["name"]);
$imagesql = "INSERT INTO Image (ImageFile) VALUES (?)";
if (!$insert = $mysqli->prepare($imagesql)) {
// Handle errors with prepare operation here
}
//Don't pass data directly to bind_param store it in a variable
$insert->bind_param("s",$img);
//Assign the variable
$img = 'ImageFiles/'.$_FILES['fileImage']['name'];
$insert->execute();
if ($insert->errno) {
// Handle query error here
}
$insert->close();
$lastID = $mysqli->insert_id;
$imagequestionsql = "INSERT INTO Image_Question (ImageId, SessionId, QuestionId) VALUES (?, ?, ?)";
if (!$insertimagequestion = $mysqli->prepare($imagequestionsql)) {
// Handle errors with prepare operation here
echo "Prepare statement err imagequestion";
}
$qnum = (int)$_POST['numimage'];
$insertimagequestion->bind_param("isi",$lastID, $sessid, $qnum);
$sessid = $_SESSION['id'] . ($_SESSION['initial_count'] > 1 ? $_SESSION['sessionCount'] : '');
$insertimagequestion->execute();
if ($insertimagequestion->errno) {
// Handle query error here
}
$insertimagequestion->close();
Here's the output of SHOW CREATE TABLE for the Image Table, Image_Question Table and also the Question Table as the Image_Question Table relates to that table:
Image Table:
CREATE TABLE `Image` (
`ImageId` int(10) NOT NULL AUTO_INCREMENT,
`ImageFile` varchar(250) NOT NULL,
PRIMARY KEY (`ImageId`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8
Image_Question Table:
CREATE TABLE `Image_Question` (
`ImageQuestionId` int(10) NOT NULL AUTO_INCREMENT,
`ImageId` int(10) NOT NULL,
`SessionId` varchar(10) NOT NULL,
`QuestionId` int(5) NOT NULL,
PRIMARY KEY (`ImageQuestionId`),
KEY `FK_QuestionImage` (`ImageId`),
KEY `questionId` (`QuestionId`),
KEY `sessionId` (`SessionId`),
CONSTRAINT `FK_Image_Question` FOREIGN KEY (`SessionId`) REFERENCES `Question` (`SessionId`) ON DELETE CASCADE,
CONSTRAINT `FK_question` FOREIGN KEY (`QuestionId`) REFERENCES `Question` (`QuestionId`) ON DELETE CASCADE,
CONSTRAINT `FK_QuestionImage` FOREIGN KEY (`ImageId`) REFERENCES `Image` (`ImageId`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8
Question Table:
CREATE TABLE `Question` (
`SessionId` varchar(10) NOT NULL DEFAULT '',
`QuestionId` int(5) NOT NULL,
`QuestionContent` varchar(5000) NOT NULL,
`NoofAnswers` int(2) NOT NULL,
`AnswerId` int(10) NOT NULL AUTO_INCREMENT,
`ReplyId` varchar(2) NOT NULL,
`QuestionMarks` int(4) NOT NULL,
`OptionId` varchar(3) NOT NULL,
PRIMARY KEY (`SessionId`,`QuestionId`),
KEY `FK_Option_Table` (`OptionId`),
KEY `FK_IndividualQuestion` (`QuestionId`),
KEY `FK_Reply` (`ReplyId`),
KEY `FK_AnswerId` (`AnswerId`)
) ENGINE=InnoDB AUTO_INCREMENT=76 DEFAULT CHARSET=utf8
$img = 'ImageFiles/'.$_FILES['fileImage']['name'];
$insert->bind_param("s",$img);
Use this instead of
$insert->bind_param("s",$img);
//Assign the variable
$img = 'ImageFiles/'.$_FILES['fileImage']['name'];

Categories