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.
Related
i have these set of tables
CREATE TABLE `staff` (
`id` mediumint(8) NOT NULL AUTO_INCREMENT,
`uid` varchar(128) NOT NULL,
`name` varchar(128) NOT NULL,
`deptname` varchar(128) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO `staff` (`id`, `uid`, `name`, `deptname`) VALUES
(1,'A100','John','Finance'),
(2,'A101','Joana','ICT'),
(3,'A103','Darrel','Maintenance'),
(4,'A104','Smith','HR');
CREATE TABLE `department` (
`id` mediumint(8) NOT NULL AUTO_INCREMENT,
`deptid` int(11) UNSIGNED NOT NULL DEFAULT '0',
`deptname` varchar(128) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO `department` (`id`, `deptid`, `deptname`) VALUES
(1,'100','ICT'),
(2,'200','Finance'),
(8,'300','HR'),
(11,'400','Maintenance'),
(12,'500','Backup');
CREATE TABLE `new_staff` (
`id` mediumint(8) NOT NULL AUTO_INCREMENT,
`uid` varchar(128) NOT NULL,
`name` varchar(128) NOT NULL,
`deptid` int(11) UNSIGNED NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO `new_staff` (`id`, `uid`, `name`, `deptid`) VALUES
(1,'A100','John','600'),
(2,'A103','Darrel','400'),
(3,'A104','Smith','300'),
(4,'A101','Joana','500'),
(5,'A105','Fran','800');
i would like to update the deptid field in the new_staff table to have the correct deptid as listed in the department table
in the new_staff table deptid are currently wrong for John and Joana
this is what i tried so far
// list all deptid exists
$result=$mysqli->query("SELECT deptid FROM department");
while ($rows=mysqli_fetch_array($result))
{$deptid[]=$rows['deptid'];}
$deptidarray = implode(', ', $deptid);
echo "<br>";
//echo "$deptidarray<br>";
$query=$mysqli->query("SELECT deptid from new_staff WHERE deptid not in ($deptidarray)");
echo "<br>";
$rowtotal = mysqli_num_rows($query);
if($rowtotal>0){
while ($row=mysqli_fetch_array($query))
{
$deptid=$row['deptid'];
// echo "$deptid,";
//$query=$mysqli->query("UPDATE new_staff set deptid='$deptid' WHERE ");
}
}
else
{
// not found
}
is this possible to do entirely in mysql?
UPDATE new_staff AS ns
JOIN staff AS s ON
ns.uid = s.uid // 1. Get same users from 2 tables
JOIN department AS d ON
s.deptname = d.deptname // 2. Get department
SET ns.deptid = d.deptid // 4. Update correct department id
WHERE ns.deptid != d.deptid; // 3. Get users where department is incorrect
Run SELECT query first before updating to verify the updates.
SELECT ns.*, d.deptid AS new_dept_id
FROM new_staff AS ns
JOIN staff AS s ON
ns.uid = s.uid
JOIN department AS d ON
s.deptname = d.deptname
WHERE ns.deptid != d.deptid;
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.
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)");
I got this table
CREATE TABLE IF NOT EXISTS `set_indice_cuestionarios` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`cuestionario` int(11) NOT NULL,
`fecha` date NOT NULL,
`hora` time NOT NULL,
`aplico` varchar(100) NOT NULL,
`cliente` int(11) NOT NULL,
`tienda` int(11) NOT NULL,
`status` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
UNIQUE KEY `tienda` (`tienda`),
UNIQUE KEY `cuestionario` (`cuestionario`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
And this is my SQL sentence:
$sql_indice = "INSERT INTO set_indice_cuestionarios (cuestionario, fecha, hora, aplico, cliente, tienda) values('$cuestionario','$fecha','$hora','$aplico','$cliente','$tienda') ON DUPLICATE KEY UPDATE cuestionario = '$cuestionario', fecha = '$fecha', hora = '$hora', aplico = '$aplico', cliente = '$cliente', status = 0";
I want to Update a row if $tienda = tienda and $cuestionario = cuestionario and to Insert a new one if the any of the values doesn't match.
The Update is happening when both values match but when I only change $cuestionario it Updates the table, instead of inserting a new record, and when I only change $tienda it does the Insert. I have no idea what I' am doing wrong. Thank you in advance!
When registering my first user in table 'users' the id is the same value as user_id in the linking table,1, (language). However, when I register another user (id2 in users) the user_id in language is still 1. See SQL:
CREATE TABLE `language` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`native` varchar(30) NOT NULL,
`other` varchar(30) NOT NULL,
`other_list` varchar(9) NOT NULL,
`other_read` varchar(9) NOT NULL,
`other_spokint` varchar(9) NOT NULL,
`other_spokprod` varchar(9) NOT NULL,
`other_writ` varchar(9) NOT NULL,
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;
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 ;
This is my PHP code:
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'") or
die (mysql_error());
list($id) = mysql_fetch_row($result);
session_start();
$_SESSION['user_id']= $id;
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();
Would appreciate any help!
I think this is because your initial select query is selecting all users that are not banned
So need to change the query to filter by the new user:
"SELECT `id` FROM users WHERE `banned` = '0' and id=" . $_SESSION['$user_id'];
The reason why the user_id field kept getting populated as 1 was because mysql_fetch_row was getting the first record which was user id 1.
So if you filter it by the new user, mysql_fetch_row should get the id of the new user.
EDIT
I'm just looking at the code again, and it looks like you do not store the user id in php after you insert it, so your user_id for $_SESSION is null.
So my above example will not work. Instead of the above query, use the following function to get the id of your newly created user. You call this function after you run your insert query. That function will get the new of your newly created user.
mysql_insert_id()
http://php.net/manual/en/function.mysql-insert-id.php
EDIT 2
Ok, since mysql_insert_id() didn't work for you, maybe you can try the following. I just changed your select query to order by id desc.
$result = mysql_query("SELECT `id` FROM users WHERE `banned` = '0' order by id desc")
Just a note, this is probably not the best solution. But on a low traffic website it should be fine. To make the query a bit more accurate, you'd want to search for the user id based on a unique field like a username or email. This would make sure you get the correct id back.
EDIT 3
Here is an example of checking for the user's email. This is just the mysql query, you'll have to adjust this for php. Sorry I'm in class right now.
"SELECT `id` FROM users WHERE `banned` = '0' and email='user#email.com' limit 1