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.
Related
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.
I have one table called Master and it has four columns called id, A, B and C.
When I update the table, I need to modify the specific single column that a user selected. For example, if a user selected column A then only A records will get updated in the database. If the user selects C then only C records will updated.
Below is the code I tried, but it is updating all columns. Would you help me in this?
$column_name=$row['column_name'];//A,B,C
if (isset($result->num_rows) > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$A=$row['A'];
$B=$row['B'];
$C=$row['C'];
}}
UPDATE Master SET $column_name='$A'+20, $column_name='$B'+30, $column_name='$C'+50 WHERE user_id='$id'";
Although your requirement is not fully clear to me so then i think it
will be helped you to meet your requirement. It is a dynamic solution. If it's not you can clarify your requirement i will must be try my best to resolve it. Thanks for asking.
* table schema is stakcoverflow
* table name is master_tbl
* fields name
id | a | b | c
<?php
$myHost = "localhost"; // use your real host name ex. myDomainName.com
$myUserName = "root"; // use your real login user name ex. myUserName
$myPassword = ""; // use your real login password ex. myPassword
$myDataBaseName = "stakcoverflow"; // use your real database name ex. myDataBaseName
$con = mysqli_connect( "$myHost", "$myUserName", "$myPassword", "$myDataBaseName" );
if( !$con ) // == null if creation of connection object failed
{
// report the error to the user, then exit program
die("connection object not created: ".mysqli_error($con));
}
if( mysqli_connect_errno() ) // returns false if no error occurred
{
// report the error to the user, then exit program
die("Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
}
$sql="SELECT a,b,c,id FROM master_tbl ORDER BY id";
$affectedrowsno = 0;
if ($result=mysqli_query($con,$sql))
{
// Get field information for all fields
while ($fieldinfo=mysqli_fetch_field($result))
{
$column_name = $fieldinfo->name;
// Get field information for all fields
while ($row=mysqli_fetch_assoc($result))
{
$a = $row['a'];
$b = $row['b'];
$c = $row['c'];
$id = $row['id'];
$sql = "UPDATE master_tbl SET $column_name=$a+20, $column_name=$b+50, $column_name=$c+80 WHERE id=$id";
mysqli_query($con,$sql);
$affectedrowsno += count(mysqli_affected_rows($con));
}
}
echo "Affected rows = " . $affectedrowsno;
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
?>
You can use if statement:
$column_name=$row['column_name'];//A,B,C
if (isset($result->num_rows) > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$A=$row['A'];
$B=$row['B'];
$C=$row['C'];
}}
if($column_name == 'A'){
UPDATE Master SET A='$A'+20 WHERE user_id='$id'";
} elseif($column_name == 'B'){
UPDATE Master SET B ='$B'+30 WHERE user_id='$id'";
}elseif($column_name == 'C'){
UPDATE Master SET C ='$C'+50 WHERE user_id='$id'";
}
}
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!).
I wrote a simple code which is supposed to check if the entry field is empty or not and if it is not empty, content that is entered in that field should be the name of the newly created database TABLE. But I'm having a problem with the part where the code needs to check if the table with that name already exists or not. This is what I have so far:
include 'conn.php';
$entry_name = $_POST['entry_name'];
// Check if the field is empty
if(empty($_POST['entry_name'])) {
echo "Please, fill the name field!";
}
// If the field is full
else {
// Check for the duplicated table names
$result = mysql_query(**???**);
if($result == $entry_name) {
die("Entry with that name already exists, choose a different name!");
}
// If there are no tables with entered name, create the new table
else {
$entry_name = mysql_real_escape_string($_POST['entry_name']);
mysql_query("CREATE TABLE `" . $entry_name . "` ( first VARCHAR(30), second VARCHAR(30))");
echo "$entry_name created successfully!";
}
}
The part with the question marks is where I don't know what exactly to do.
Best way to do that is to query information schema DB. It contains all information about existing DBs and tables. But mysql 5 only.
SELECT *
FROM `TABLES`
WHERE `TABLE_SCHEMA` = 'your_database_name'
AND `TABLE_NAME` = 'your_table_name'
change your $result = mysql_query(**???**); to
$result = mysql_query('SELECT * FROM `TABLES` WHERE `TABLE_SCHEMA` = "your_database_name" AND `TABLE_NAME` = "'. $entry_name .'");
and than
if (mysql_numrows($result) !== 0)
don't forget to change your_database_name to your database name
Oh, and don't forget to sanitize your $entry_name. mysql_escape_string
I am creating a poll in php. I have a table with an id column.
When a user submits a choice, I want the php to first query the database and check whether the table "id" has the id of the current user.
I am pretty new at mysql, can someone help me with the query?
Try this:
$q = "SELECT id FROM table WHERE id = '".mysql_real_escape_string($_POST['user_id'])."'";
$r = mysql_query($q);
if(mysql_num_rows($r) > 0) {
echo "User ID was found in table";
} else {
echo "User ID was not found in table";
}
$qryResult = mysql_query("SELECT userid FROM idtable WHERE userid='$theIdOfUser'");
if (mysql_num_rows($qryResult) == 0)
{
// add a new vote
}
else
{
// notify the user that double voting is prohibited
}
Try not to use names like "id" to avoid conflicts with reserved words and related complications and need to use quotes