Inserting/Updating MySQL table via PHP, row will update but not insert. - php

Im not very experienced in PHP and would appreciate any help! Im am sending a username, longitude and latitude to my server using HTTP Post. I first check if the user exists in the user_info table. If it does then i try to update the maps_user_location table with that username. What i want to happen is that if the query fails, due to the username not being found in maps_user_location table, then i want it to be added. I've tried to do it with the code below.
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_localhost, $localhost);
$latitude = $_POST['latitude'];
$longitude = $_POST['longitude'];
$username = $_POST['username'];
if ($latitude != 0 && $longitude != 0) {
$query_userCheck = "SELECT * FROM user_info WHERE login_username = '".$username."';";
if ( mysql_query($query_userCheck) ) {
$query_updateLocation = "UPDATE `maps_user_location` SET `lat` = '".$latitude."',`long` = '".$longitude."' WHERE
`login_username` = '".$username."';";
if ( !mysql_query($query_updateLocation) ){
$query_newLocation = "INSERT INTO `maps_user_location` ( `id` ,`login_username` ,`lat` ,`long` ,`track`)
VALUES ( NULL , '".$username."', '".$latitude."', '".$longitude."', '0');";
mysql_query($query_newLocation);
}
}
}
When i execute the code, it goes through without a hitch. The problem is that a row is never inserted if the username does not exist already, the row does update if the username exists though. Additionally, when i add a row manually, the id column seems to increment after every request (the sequence will go 1,2,3,4,10,11,12...etc [the ids 5-9 do not exist]). I have a feeling that it has to do with the 'WHERE' in '$query_updateLocation'. Anyone have any clue as to why this happens?

You can simply do that in a single query, Use INSERT...ON DUPLICATE KEY UPDATE
INSERT INTO maps_user_location ( login_username , lat, long, track)
VALUES ('".$username."', '".$latitude."', '".$longitude."', '0')
ON DUPLICATE KEY UPDATE
lat = '".$latitude."' ,
long = '".$longitude."'
but before anything else, make sure that you have a UNIQUE CONSTRAINT on the column login_username. If you have not added, you can alter your table using this command
ALTER TABLE maps_user_location ADD UNIQUE (login_username);

Related

Insert Multiple Value into table MySQL if not exists

I have a table with 3 columns (ID, username, full name), I want the ID to be AUTOINCREMENT. I want to insert into the table only if it does not already exist in the table.
This is my Code:
$fullName = $_POST['fullname'];
$username = $_POST['username'];
$dbhost = "localhost";
$dbname = "databasename";
$dbusername = "root";
$dbpassword = "";
$link = new PDO("mysql:host=$dbhost;dbname=$dbname","$dbusername","");
$statement = $link->prepare('INSERT INTO accounts (username, fullname)
VALUES (:username, :fname)');
$statement->execute([
'fname' => $fullName,
'username' => $usernameget,
]);
If your id is already autoncrement then you no need to mention in query.
You can simply write below query
insert into accounts (username,fullname) values( $username , $fullname )
you can do this with if else condition in PHP
$fullname = $_POST['fullname'];
$username = $_POST['username'];
$chk = mysqli_query("select * FROM `accounts` where fullname='$fullname' and username='$username'");
$rs = mysqli_fetch_array($chk);
if($rs == "")
{
$ins = mysqli_query("INSERT INTO `accounts`(fullname,username) VALUES ('$fullname','$username'))";
}
else{
echo "Duplicate entry";
}
or you can do this by SQL Query also.
INSERT INTO accounts(username,fullname)
SELECT * from (SELECT '$username', '$fullname') AS tmp
WHERE NOT EXISTS
(SELECT username FROM accounts WHERE username='$username')
There's several things to fix here.
Don't specify column values if you don't need to, or don't care about the value. Only specify if necessary or relevant. In this case id should be omitted.
Always use placeholder values for your user data. Never put $_GET or $_POST data directly in a query.
To avoid duplication add a UNIQUE constraint on the table.
To fix that you do adjust your code:
// Enable exceptions, avoiding the need for manual error checking
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// Try and keep the order of things like this consistent through your code
$username = $_POST['username'];
$fullname = $_POST['fullname'];
// Here using a short, common name for the database handle $db
$db = new mysqli("localhost","root","","database");
// Prepare your insert first as a query with no data, only placeholders
$db->prepare("insert into accounts (username,fullname) values(?,?)");
// Bind the data to the placeholders, here two string ("s") values.
$db->bind_param('ss', $username, $fullname);
// Execute the query
$db->execute();
To add the UNIQUE constraints use CREATE INDEX:
CREATE INDEX idx_accounts_username (username);
CREATE INDEX idx_accounts_full_name (full_name);
That has to be run in your MySQL shell, not PHP.
When a UNIQUE constraint is in place MySQL will not allow duplicate data. Note that NULL values don't count, and can be "duplicated". Set NOT NULL on your columns to force them to be completely unique.
As your id is autoincrement primary key, so you can create or update it with:
insert into accounts (username,fullname) values( $username , $fullname ) on duplicate key update username = '$username',fullname = '$fullname'
To get correct answers, a question must be asked with as much explanation as possible. you should atleast tell what have you done and then what are you getting.
As far as i have understood, to achieve your goal, the table structure must be changed and inserting query also.
Remember to accept the answer and click the upvote button if the answer satisfies you,else give more information in the question, so that members here, can give right answers.
If you understand table creating queries go to bottom of this answer or else do as follows:
if you use gui to create table,
1. click on create new table.
2. in the right pane give table name and column names as shown. (dont give space in 'full name' instead give 'full_name' or 'fullname')
3. scroll the winow to the right till you see A_I column as shown.
4. tick the first line (which we have used as id), 'add index' box will appear.
just click here go (at the bottom).
you will be redirected to table list as shown.
6. open (click) your table again.
7. click on structure.
now suppose you don't want duplicates in 'username' column, click this column and click on 'unique' as shown
if you don't want duplicate when both the columns' value together, click both the columns and then click 'unique' as shown
if you understand create table commands:here is the sql for above:
CREATE TABLE accounts (
id int(11) NOT NULL AUTO_INCREMENT,
username varchar(25) NOT NULL,
fullname varchar(55) NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY username (username)
) ENGINE=MyISAM DEFAULT CHARSET=latin1
with above table structure records will be autoincremented and duplicate names will not be added. (remember to handle duplicate entries error in you inserting querie withINSERT IGNORE INTOwith this your query will be:
$statement = $link->prepare('INSERT IGNORE INTO accounts (username, fullname)
VALUES (:username, :fname)');
or you can also useON DUPLICATE KEY)
First set your primary key (eg. id) if not set as auto increment
Second use multiple insertion value
INSERT IGNORE INTO accounts (username,fullname) VALUES ("p","k"),("c","s");
IGNORE keyword is use to duplicate
IF you want to see with PDO

insert or replace id exists or is difrent

I have this code in php to insert into database
$sqlx="INSERT INTO bruno_wallet (foto, data, nome, evento,horarios,obs,horas,valorhora,totalparcial,props,id_do_mes,nome_id )
VALUES ('$ii', '$data','$nome[0]','$evento' ,'$horarios','$obs','$numeros_horas','$valor_horas','$total_parcial','$props',' $id_postt','$nomeid') " ;
but it always inserts news values.
I want to : insert if its new and replace if old values if it exists
You shouldn't be using the INSERT command then. First find if it already is in your database then insert or leave it as it is.
You can use DUPLICATE KEY UPDATE if you have only primary key in table.
Note than: if you have any other key like Unique Key etc than it will not work.
$sqlx="INSERT INTO bruno_wallet (foto, data, nome, evento,horarios,obs,horas,
valorhora,totalparcial,props,id_do_mes,nome_id )
VALUES ('$ii', '$data','$nome[0]','$evento' ,'$horarios','$obs',
'$numeros_horas','$valor_horas','$total_parcial','$props','$id_postt','$nomeid')
ON DUPLICATE KEY UPDATE
foto = '$ii', data = '$data', nome = '$nome[0]', evento = '$evento', horarios = '$horarios',
obs = '$obs', horas = '$numeros_horas', valorhora = '$valor_horas',
totalparcial = '$total_parcial', props = '$props', id_do_mes = '$id_postt', nome_id = '$nomeid'
";
Explanation:
From dev.mysql.com: You can use the VALUES(col_name) function in the
UPDATE clause to refer to column values from the INSERT portion of the
INSERT ... ON DUPLICATE KEY UPDATE
If foto is a primary key than after ist insertion every time this query will update the record.
Hi here is simple and easy solution try it.
$result = mysql_query("SELECT * FROM bruno_wallet WHERE foto = '$ii' "); //in where condition add whatever condition you want
if( mysql_num_rows($result) > 0) {
$sqlx = "UPDATE bruno_wallet SET foto ='$ii', data = '$data', nome = '$nome[0]', evento = '$evento' ,horarios = '$horarios',obs = '$obs',horas = '$numeros_horas',valorhora = '$valor_horas',totalparcial = '$total_parcial',props = '$props',id_do_mes = ' $id_postt',nome_id = '$nomeid' WHERE foto = '$ii' "; //in where condition add whatever condition you want
}
else
{
$sqlx="INSERT INTO bruno_wallet (foto, data, nome, evento,horarios,obs,horas,valorhora,totalparcial,props,id_do_mes,nome_id )
VALUES ('$ii', '$data','$nome[0]','$evento' ,'$horarios','$obs','$numeros_horas','$valor_horas','$total_parcial','$props',' $id_postt','$nomeid') " ;
}
You cannot do that this way, an INSERT command is always an additional row in your database. You can however do something with subqueries, But the better practice is to do this in code.
You should run SELECT using the columns and values you have, If exists run a insert else run a update.
The problem you present is impossible to solve, since the database will not have anything to update if all columns match, I hope you understand how that would work, and that the way you intend it is not logical. Also you are not mentioning what your "matchcolumns" are. so if what matches what it should be an update...
If you do need to proceed this way, Please provide us more information so we can assist
If you are using MYSQL you can use INSERT ... ON DUPLICATE KEY UPDATE from Mysql manual
When doing an insert where a unique key is present the existing record will be updated with the fields you specify.
The easiest way to solve this is to check if the data sent exists in the database already. If the data is already in the database run an update query and run insert if not.
Run this first
Select * from bruno_wallet where nome_id='$nomeid';
Now fetch the data and set if to any variable. For this purpose am going to call it $info
Now run
if(!$info)
{
"INSERT INTO bruno_wallet (foto, data, nome, evento,horarios,obs,horas,valorhora,totalparcial,props,id_do_mes,nome_id )
VALUES ('$ii', '$data','$nome[0]','$evento' ,'$horarios','$obs','$numeros_horas','$valor_horas','$total_parcial','$props',' $id_postt','$nomeid') " ;
}else{
Run update query
}
`

How to get a tuple's values that is inserted into PostgreSql db using php?

I am trying to insert a tuple into PostgreSql using PHP. After inserting the tuple I want to get the value of one of the columns of the inserted row. This column value is generated automatically by the db as it is defined as SERIAL in DDL.
$query = "INSERT INTO posts VALUES('$title','$msg',$x,$y,'$me')";
$result = pg_query($dbh,$query);
if (!$result) {
$status = 0;
} else {
$status = 1;
}
$row = pg_fetch_assoc($result);
$pID = $row['postID'];
$array = array(
'status' => $status,
'pID' => $pID
);
#Delete query is only for checking if the code is working.
$query = "DELETE FROM posts WHERE postID='$pID'";
$result = pg_query($dbh,$query);
The table 'posts' has following DDL:
CREATE TABLE posts
( title CHAR(20),
content CHAR(42),
x_coor INTEGER,
y_coor INTEGER,
userID CHAR(50),
time_stamp TIMESTAMP default current_timestamp,
postID SERIAL,
PRIMARY KEY(postID),
FOREIGN KEY (userID) REFERENCES users ON DELETE CASCADE);
I want to get the value of 'postID' column when I insert a row into the table 'posts' to perform additional functions based on postID. I have tried pg_fetch_assoc, pg_fetch_row, pg_fetch_object & pg_fetch_array. None of those seem to work. (I made appropriate modifications to the code when using each of those functions.)
Is there something incorrect in the code or perhaps I am missing something?
Thanks!
A good way is the returning clause:
INSERT INTO posts
VALUES('$title','$msg',$x,$y,'$me')
RETURNING id;
My PHP is a bit rusty, but it'd look something like:
$query = "INSERT INTO posts VALUES('$title','$msg',$x,$y,'$me') RETURNING id";
$result = pg_query($dbh, $query);
if ($result) {
$row = pg_fetch_row($result);
$inserted_id = $row[0];
}

prevent duplicate records in mysql table

Im creating a website for booking activities. I have 3 centres. The customer is cant book the same activity twice neither in a different centre. Im using a table in mysql which i store the infos provided by the costumers. Is there any way to filter or to check in my php code if a customer has already booked the same activity more than one time and echo an error msg?
my table(and the info im asking) contains these columns:
ID(Primary)
FirstName
LastName
Email
ContactNumber
ClassName
Week
Intensity
CentreName
$values = $_POST;
foreach ($values as &$value) {
$value = mysql_real_escape_string($value);
}
$sql1="INSERT INTO loan (loan_id)
VALUES ('$values[loan_id]')";
$result = mysql_query($sql1);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
When you create the table add the unique attribute to the fields you want to prevent, something like this
CREATE TABLE Persons
(
P_Id INT NOT NULL AUTO_INCREMENT,
LastName VARCHAR(255) NOT NULL,
FirstName VARCHAR(255),
Address VARCHAR(255),
City VARCHAR(255),
UNIQUE (P_Id)
)
If you already have created the table just edit it like this
ALTER TABLE Persons
ADD UNIQUE (P_Id)
Hope this helps you; If you do not have a unique id i believe this will suit you best on what you need; Note that this is not the full code; You need to add some to other information to fit in your question;
// Checks if the value already exist on the database
$query = SELECT EXISTS(SELECT column_name FROM table_name WHERE
condition LIMIT 1)
// If condition is not met it will proceed with save
if (mysql_num_rows(!$query) > 0) {
echo "Activity Booked";
} else { // If condition is met it will echo an error message
echo "Unable to booked activity"; }
You need to create a unique (composite) index on the column(s) that you wish to be unique. You can disregard your PK when making your unique index. In your case your sql would look something like:
Alter table yourtablename
add unique index idx_unq(`LastName`, `FirstName`, `Email`, `ContactNumber` `ClassName`, `Week`, `Intensity`, `CentreName`);
Then do an INSERT IGNORE INTO instead of an INSERT INTO.
This post may also help you.
"INSERT INTO .. ON DUPLICATE KEY UPDATE" Only inserts new entries rather than replace?
In order to see if record already exist in table you must first "test" to see if that exact record exist in your table. This is to be done before the 'Insert IGNORE Into' in your logic. Using the variables your code would look something like this:
$testcount = "Select count(`LastName`, `FirstName`, `Email`, `ContactNumber` `ClassName`, `Week`, `Intensity`, `CentreName`)
from yourtablename
where
(LastName = '$LastName' AND FirstName= '$FirstName' AND Email= '$EMAIL' AND ContactNumber= '$ContactNumber' AND ClassName= '$ClassName' AND Week= '$Week' Intensity = '$Intensity' AND CentreName = '$CentreName' )";
This query will give you back (assuming there are no duplicates already in the table) a 0 or a 1 and store it in your $testcount variable. This can then be used to either determine based on the value to insert the record into the table or print a message to end user informing them that it already exist.
I am not sure how you want to structure the php code but the psuedocode would look something like:
If $testcount = 1 then do your insert.
else if $testcount = 0 then echo your message.

PHP & MYSQL Is this MySQL Syntax correct for UPDATE/INSERT IF EXISTS

My plan is to update/insert existing/new records into a database from an external, i have the information set to go into the database, but cannot check if it exists already.
my first attempted at doing database stuff
$link = resdb::connect();
$q = "IF ( EXISTS ( SELECT * FROM property AS this WHERE this.name = $propertyname ) )"
."begin"
// UPDATE PROPERTY IF IT EXISTS
."UPDATE property (name, propertylocation, propertyrating, propertytype)"
."SET ($propertyname, $locationid, $ratingid, $typeid)"
."WHERE name = $propertyname"
."end"
."ELSE"
."begin"
."INSERT INTO property (name, propertylocation, propertyrating, propertytype)"
."VALUES ($propertyname, $locationid, $ratingid, $typeid)"
."end";
$r = mysqli_query($link, $q);
if($r > 0){
return true;
}
A unique id is made on completion of each row.
First create a unique index on the name column:
ALTER TABLE property ADD UNIQUE KEY(name)
Now you can use the MySql INSERT ... ON DUPLICATE KEY UPDATE...
INSERT property (name, propertylocation, propertyrating, propertytype)
VALUES ($propertyname, $locationid, $ratingid, $typeid)
ON DUPLICATE KEY UPDATE
propertylocation = VALUES(propertylocation),
propertyrating = VALUES(propertyrating),
propertytype = VALUES(propertytype)
Docs: http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
Don't forget to sanitize database inputs.

Categories