Data insert not success when using varchar as primary key? - php

This is my table
CREATE TABLE room (
room_ID VARCHAR(8),
room_name TEXT(50),
room_capacity INT(3),
room_building VARCHAR(20),
room_type VARCHAR(20),
room_desc TEXT(100),
PRIMARY KEY (room_ID)
);
and this is my insert code.
<?php
//Start session
session_start();
//Import connection
include('conn.php');
$room_ID = $_POST["room_ID"];
$room_type = $_POST["room_type"];
$room_name = $_POST["room_name"];
$room_capacity = $_POST["room_capacity"];
$room_building = $_POST["room_building"];
$room_desc = $_POST["room_desc"];
//echo $room_ID;
//echo $room_type;
//echo $room_name;
//echo $room_capacity;
//echo $room_building;
//echo $room_desc;
//Check for duplicate room ID
//if($room_ID != '') {
$qry = "SELECT room_ID FROM room WHERE room_ID = '".$room_ID."'";
$result = mysql_query($qry);
if($result) {
if(mysql_num_rows($result) > 0) {
header("location: duplicateID.php");
exit();
}
#mysql_free_result($result);
}
else {
die("Yang ini lah failed");
}
}
//Create INSERT query
$qry = "INSERT INTO room (room_ID, room_name, room_capacity, room_building, room_type, room_desc)
VALUES('$room_ID', '$room_name', '$room_capacity', '$room_building', '$room_type', '$room_desc')";
$result = #mysql_query($qry);
//Check whether the query was successful or not
if($result) {
header("location: addroomsuccess.php");
exit();
} else {
die("Query failed");
}?>
But the problem is, the process stuck in the first if else. But when i delete those if else, the query still failed. Why did this happen? Is it because im using varchar as the data type for the primary key?

So much wrong with this.
1) If you have a PK you will not get duplicates so your check is pointless.
2) Just insert it. If it fails, you have a duplicate or some other problem. Checking first just narrows the opportunity but it can still go wrong in a multiuser environment.
3) SQL injection - read up on it, understand it at implement SQL that avoids it (parameters).
But to answer your question, not it has nothing to do with VARCHAR as a PK - that's fine if it makes sense. #AlexandreLavoie's advice is not good or relevant (sorry!).

Related

How to check if the DB already have the data or insert new data

What I want is that php check if the client IP address is the same one which in the DB if it already exists, if not to insert new data.
well, it works if the client isn't already inserted in the database, but if he already exists php is skipping the update and trying to insert it again in the database............
I don't know whats wrong with it and couldn't figure out.
Here is my code:
<?php
$corruser = $_SESSION['user_name'];
$client_ip = $_SERVER['REMOTE_ADDR'];
require_once 'connections/dbc.php';
if (!$conn) {
echo "Error connecting the database";
exit();
} else{
$GUI = "SELECT * FROM `customers` WHERE user_name='$corruser'";
$GUI_response = mysqli_query($conn, $GUI);
if (!$row = mysqli_fetch_assoc($GUI_response)) {
echo "Error while query the database";
exit();
} else{
$customer_id = $row['customer_id'];
$check = "SELECT * FROM `users-ipdb` WHERE customer_id='$customer_id' AND user_name='$user_name' ";
$check_response = mysqli_query($conn,$check);
$check_result = mysqli_fetch_array($check_response, MYSQLI_NUM);
if ($check_result[0] > 1) {
$update_ip = "UPDATE `users-ipdb` SET `client_ip`='$client_ip' WHERE customer_id='$customer_id' AND user_name='$corruser' ";
$update_ip_result = mysqli_query($conn, $update_ip);
if (!$update_ip_result) {
echo "ERROR UPDATING DATA BASE";
exit();
}
} else{
$insert_new = "INSERT INTO `users-ipdb`(`customer_id`, `user_name`,`client_ip`) VALUES ('$customer_id','$corruser','$client_ip')";
$insert_new_result= mysqli_query($conn, $insert_new);
if (!$insert_new_result) {
echo "Error inserting new data in the database";
exit();
}
}
}
}
?>
I think you made an error with this code :
$check = "SELECT * FROM `users-ipdb` WHERE customer_id='$customer_id' AND user_name='$user_name' ";
$user_name variable doesn't exist, you should replace it with $corruser
That's why the code never goes into the UPDATE
First, make sure that your condition does work as expected. If customer_id is not a number the following line:
if ($check_result[0] > 1) {
can be possibly evaluated as if(0 > 1) let you read this:
Comparing String to Integer gives strange results.
The other comments mention "UPSERTS" which are explained here https://mariadb.com/kb/en/library/insert-on-duplicate-key-update/
The basic idea is that you can do
INSERT INTO `users-ipdb`(`customer_id`, `user_name`,`client_ip`)
VALUES ('$customer_id','$corruser','$client_ip')"
ON DUPLICATE KEY UPDATE client_ip='$client_ip';
and you get rid of the all the php logic. For this to work properly customer_id and user_name must be both part of the PRIMARY KEY.
If you need to query multiple tables, you can use joins - if you use ON DUPLICATE KEY UPDATE you don't need them, but still a good thing to know - https://mariadb.com/kb/en/library/join-syntax/
Last, but not least - it is a good habit to escape any value which may come from other sources. Maybe it is not your case, but some people tend to create usernames like Joe';DROP TABLE mysql.user;SELECT ' and it will destroy your database, because your query will become
SELECT * FROM `users-ipdb` WHERE customer_id='$customer_id' AND user_name='Joe';DROP TABLE mysql.user;SELECT ''
So be careful.

Duplicate entry '1' for key 'PRIMARY' when updating the table

I have a problem when trying to update table after checking row. Not sure if the "if" statement is wrong, however I'm not quite sure, why the UPDATE sql is returning this error. I wouldn't be suprised if INSERT did that.
Here's part of code:
$sql = "SELECT user_id FROM players WHERE user_id = '$id'";
$result = $connect->query($sql);
if($result->num_rows > 0)
{
$sql = "UPDATE players SET user_id = '$Player->user_id', display_name = '$Player->display_name', attackPower = '$Player->attackPower]', defensePower = '$Player->defensePower'";
if($connect->query($sql) === TRUE)
{
echo 'Table has been successfully updated.';
}else{
echo 'There has been a problem with updating the "players" table. <br>Error: '.$connect->error;
}
}else{
$sql = "INSERT INTO players(user_id, display_name, attackPower, defensePower) VALUES('$Player->user_id', '$Player->display_name', '$Player->attackPower', '$Player->defensePower')";
if($connect->query($sql) === TRUE)
{
echo'Table has been successfully migrated.';
}else{
echo'Table migration has failed.';
}
}
$connect->close();
INSERTing is working just fine. I would appreciate any advice. Thanks.
Your update query should look like:
$sql = "UPDATE `players` SET `display_name` = '{$Player->display_name}',
`attackPower` = '{$Player->attackPower}', `defensePower` = '{$Player->defensePower'}
WHERE `user_id` = '{$Player->user_id}'";
It cause an error because Identity columns are not updateable.
You can update every columns except them:
$sql = "UPDATE players SET display_name = '$Player->display_name', attackPower = '$Player->attackPower]', defensePower = '$Player->defensePower'";
As #aynber and #Julqas said, problem was my sql was missing WHERE condition. Thanks for help.

Insert command failing [duplicate]

This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 5 years ago.
So, I'm having trouble getting data into this table. I have a similar table setup for memberships. If I change the insert into query to membership from join everything works perfectly, but as soon as I change the table to join it stops working. The table seems to be properly setup since it's basically the same as my membership table, but for some reason data will not insert. I can't think of what could be causing my problem so I'm coming to the experts.
Note that this code all works perfectly when going into a different table. Thanks in advance.
if ( isset($_POST['btn-join']) ) {
// clean user inputs to prevent sql injections
$groupID = trim($_POST['groupID']);
$groupID = strip_tags($groupID);
$groupID = htmlspecialchars($groupID);
$teamname = trim($_POST['teamname']);
$teamname = strip_tags($teamname);
$teamname = htmlspecialchars($teamname);
// Query groups to set group name
$query2 = "SELECT groupName FROM groups WHERE groupID='$groupID'";
$result2 = mysqli_query($con,$query2);
$groupquery = mysqli_fetch_array($result2,MYSQLI_ASSOC);
$groupname = $groupquery['groupName'];
// groupID validation
if (empty($groupID)) {
$error = true;
$groupIDError = "Please enter valid Group ID.";
} else {
// check email exist or not
$query3 = "SELECT groupID FROM groups WHERE groupID='$groupID'";
$result3 = mysqli_query($con,$query3);
$count = mysqli_num_rows($result3);
if($count!=1){
$error = true;
$groupIDError = "Provided Group does not exist.";
}
}
// basic teamname validation
if (empty($teamname)) {
$error = true;
$nameError = "Please enter your Team Name.";
} else if (strlen($teamname) < 3) {
$error = true;
$nameError = "Team Name must have at least 3 characters.";
}
// if there's no error, continue to signup
if( !$error ) {
$query = "INSERT INTO join(groupID,userID,groupName,teamName) VALUES('$groupID','$userID','$groupname','$teamname')";
$membership = mysqli_query($con,$query);
if ($membership) {
$errTyp = "success";
$errMSG = "Account successfully updated";
header("Location: dashboard.php");
} else {
$errTyp = "danger";
$errMSG = "Something went wrong, try again later...";
}
}
}
SQL:
CREATE TABLE IF NOT EXISTS `join` (
`jID` int(11) NOT NULL AUTO_INCREMENT,
`groupID` varchar(32) NOT NULL,
`userID` varchar(32) NOT NULL,
`groupName` varchar(35) NOT NULL,
`teamName` varchar(32) NOT NULL,
`joinDate` datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`jID`),
UNIQUE KEY `groupID` (`groupID`,`userID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
join is a reserved word in SQL. To avoid these sorts of issues, use backticks around table and column names:
$query = "INSERT INTO `join`(`groupID`,`userID`,`groupName`,`teamName`) VALUES('$groupID','$userID','$groupname','$teamname')";
$membership = mysqli_query($con,$query);
As a side note, you should really rewrite this query to use a prepared statement and then bind the variables to it. This is a SQL injection waiting to happen.

Cannot insert more than one data

Hye everyone please help me,I have a problem with my insert value which is i cannot insert more than one data.but when I look at the data value in the table,it seen like N5,N7 and N9 are missing. The error shown
"N4";"farah bt muhammad";4;"PEREMPUAN";"C5"
"N6";"Maisarah";2;"PEREMPUAN";"C2"
"N8";"haikal";4;"LELAKI";"C2"
Warning : pg_query():Query failed: ERROR: insert or update on table "nominee" violets foreign key constraint "custFK"
DETAIL: Key(cust_id)=(C2) is not present in table "customer".
<?php
$connection = pg_connect ("user = postgres password = syafiqah26 port = 5433 dbname = bengkel2 host = localhost");
$number = count($_POST["name"]);
$number1 = count($_POST["gender"]);
$number2 = count($_POST["age"]);
$number3 = count($_POST["hidden"]);
if(($number > 0)&&($number1>0)&&($number2>0)&&($number3>0))
{
for($i=0,$j=0,$k=0,$l=0; $i<$number && $j<$number1 && $k<$number2 && $l<$number3; $i++,$j++,$k++,$l++)
{
if((trim($_POST["name"][$i] != ''))&&(trim($_POST["gender"][$j] != ''))&&(trim($_POST["age"][$k] != ''))&&(trim($_POST["hidden"][$l] !='')))
{
$sql = "INSERT INTO nominee(name,gender,age,cust_Id) VALUES('".pg_escape_string($connection, $_POST["name"][$i])."','".pg_escape_string($connection, $_POST["gender"][$j])."','".pg_escape_string($connection, $_POST["age"][$k])."','".pg_escape_string($connection, $_POST["hidden"][$l])."')";
pg_query($connection, $sql);
}
}
echo "Data Inserted";
}
else
{
echo "Please Enter Name";
}
pg_close($connection);
?>
A foreign key is a database constraint that seeks to maintain "order" as deemed by the database creator. In this case, you cannot have a "nominee" who is not in the customer table.
Either be certain you have the proper id for the nominee from the user table, or if it is a new user, insert the customer first, then get the customer's id and use it to insert the nominee.

Update value only if Null php/mysql

Thanks for checking out my question. I am trying to only update a value in my database if that field is null (so existing users won't be overwritten if someone tries to signup for a spot that is all ready taken and an error message will be output). I have listed below 2 of the most recent scripts I have tried. The first script works for updating the database if the select statement is not there but will overwrite users if entered for the same day and time. Thanks everybody!
$sql = ("SELECT `player1` FROM `users` where id = '$id' and Times = '$time'");
$result = $conn->query($sql);
if ($result->fetch_assoc === NULL) {
$update_player = ("UPDATE users SET player1 = '$name' where id = '$id' AND Times = '$time'")
if($update_player){
echo "Date for $name inserted successfully!";
}
}
else {
echo 'That spot is all ready taken!';
}
//2nd script
$query=mysql_query("UPDATE users SET
player1 = isNULL (player1, $name)
where id = '$id' AND Times = '$time'" );
if($query){
echo "Data for $name inserted successfully!";
}
else {
echo 'That spot is all ready taken!';
}
The following code should do the trick:
$query=mysql_query("UPDATE users SET
player1='$name'
where id = '$id' AND Times = '$time' AND player1 IS NULL" );
if(mysql_affected_rows() == 1){
echo "Data for $name inserted successfully!";
}
else {
echo 'That spot is all ready taken!';
}
Note that you should use pdo or mysqli functions instead.
Try This.
while($row = $result->fetch_assoc) {
if($row['player1'] == NULL){
$update_player = ("UPDATE users SET player1 = '$name' where id = '$id' AND Times = '$time'")
}

Categories