If inputs exist, dont insert, else insert PHP mysql - php

I've just started with php, and i wondered if anyone can help.
i have this
$sql="INSERT INTO $tbl_name SET date='$mydate' , event='$myevent'";
$result=mysql_query($sql);
I need to know how to make it see if the event exists, and if it does i need it to do nothing, if it doesn't then insert it!

split it into 2 queries:
1) check if event exists. If yes then do nothing, else insert a new event
2) continue with your query. this way the event will allays exist when inserting your data

This is something that can be done through MySQL alone.
Setup a unique key for the event column by running the following MySQL Command on your table:
CREATE UNIQUE INDEX `i_event` ON `TABLE_NAME_GOES_HERE` (`event`);
For more information: http://dev.mysql.com/doc/refman/5.0/en/create-index.html
Do this for every possible table you expect to see in the $tbl_name variable.
Then, change your PHP Query:
$sql="INSERT IGNORE INTO $tbl_name SET date='$mydate' , event='$myevent'";
$result=mysql_query($sql);
For more information on INSERT IGNORE: http://dev.mysql.com/doc/refman/5.5/en/insert.html
INSERT IGNORE simply does as it states... it will try to insert the row unless it fails validation (in this case from an index that you declared HAS to be unique).

Try:
$query = mysql_query("SELECT $myevent from $tbl_name ")
$rows = mysql_num_rows($query)
if ($num_rows > 0) {
// do nothing
}
else {
$sql = "INSERT INTO $tbl_name SET date='$mydate' , event='$myevent'";
$result = mysql_query($sql);
}
As a sidenote: mysql_ functions are deprecated and it's recommended to switch to mysqli or PDO.

Related

How can i get the last inserted id using select * from query? [duplicate]

I have a table into which new data is frequently inserted. I need to get the very last ID of the table. How can I do this?
Is it similar to SELECT MAX(id) FROM table?
If you're using PDO, use PDO::lastInsertId.
If you're using Mysqli, use mysqli::$insert_id.
If you're still using Mysql:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
But if you have to, use mysql_insert_id.
there is a function to know what was the last id inserted in the current connection
mysql_query('INSERT INTO FOO(a) VALUES(\'b\')');
$id = mysql_insert_id();
plus using max is a bad idea because it could lead to problems if your code is used at same time in two different sessions.
That function is called mysql_insert_id
With PDO:
$pdo->lastInsertId();
With Mysqli:
$mysqli->insert_id;
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
It's ok. Also you can use LAST_INSERT_ID()
What you wrote would get you the greatest id assuming they were unique and auto-incremented that would be fine assuming you are okay with inviting concurrency issues.
Since you're using MySQL as your database, there is the specific function LAST_INSERT_ID() which only works on the current connection that did the insert.
PHP offers a specific function for that too called mysql_insert_id.
Try this should work fine:
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$query = "INSERT blah blah blah...";
$result = mysqli_query($link, $query);
echo mysqli_insert_id($link);
Clean and Simple -
$selectquery="SELECT id FROM tableName ORDER BY id DESC LIMIT 1";
$result = $mysqli->query($selectquery);
$row = $result->fetch_assoc();
echo $row['id'];
To get last inserted id in codeigniter
After executing insert query just use one function called insert_id() on database, it will return last inserted id
Ex:
$this->db->insert('mytable',$data);
echo $this->db->insert_id(); //returns last inserted id
in one line
echo $this->db->insert('mytable',$data)->insert_id();
It's ok to use mysql_insert_id(),
but there is one specific note about using it, you must call it after executed INSERT query, means in the same script session.
If you use it otherwise it wouldn't work correctly.
You can get the latest inserted id by the in built php function mysql_insert_id();
$id = mysql_insert_id();
you an also get the latest id by
$id = last_insert_id();
It's sad not to see any answers with an example.
Using Mysqli::$insert_id:
$sql="INSERT INTO table (col1, col2, col3) VALUES (val1, val2, val3)";
$mysqli->query($sql);
$last_inserted_id=$mysqli->insert_id; // returns last ID
Using PDO::lastInsertId:
$sql="INSERT INTO table (col1, col2, col3) VALUES (val1, val2, val3)";
$database->query($sql);
$last_inserted_id=$database->lastInsertId(); // returns last ID
NOTE: if you do multiple inserts with one statement mysqli::insert_id will not be correct.
The table:
create table xyz (id int(11) auto_increment, name varchar(255), primary key(id));
Now if you do:
insert into xyz (name) values('one'),('two'),('three');
The mysqli::insert_id will be 1 not 3.
To get the correct value do:
mysqli::insert_id + mysqli::affected_rows) - 1
This has been document but it is a bit obscure.
I prefer use a pure MySQL syntax to get last auto_increment id of the table I want.
php mysql_insert_id() and mysql last_insert_id() give only last transaction ID.
If you want last auto_incremented ID of any table in your schema (not only last transaction one), you can use this query
SELECT AUTO_INCREMENT FROM information_schema.TABLES
WHERE TABLE_SCHEMA = 'my_database'
AND TABLE_NAME = 'my_table_name';
That's it.
Using MySQLi transaction I sometimes wasn't able to get mysqli::$insert_id, because it returned 0. Especially if I was using stored procedures, that executing INSERTs. So there is another way within transaction:
<?php
function getInsertId(mysqli &$instance, $enforceQuery = false){
if(!$enforceQuery)return $instance->insert_id;
$result = $instance->query('SELECT LAST_INSERT_ID();');
if($instance->errno)return false;
list($buffer) = $result->fetch_row();
$result->free();
unset($result);
return $buffer;
}
?>
Use mysqli as mysql is depricating
<?php
$mysqli = new mysqli("localhost", "yourUsername", "yourPassword", "yourDB");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
// Conside employee table with id,name,designation
$query = "INSERT INTO myCity VALUES (NULL, 'Ram', 'Developer')";
$mysqli->query($query);
printf ("New Record has id %d.\n", $mysqli->insert_id);
/* close connection */
$mysqli->close();
?>
I tried
mysqli_insert_id($dbConnectionObj)
This returns the current connection's last inserted id, so if you are managing your connections properly this should work. Worked for me at least.

Select and update not working

I have a table viewer with id, ip, date_last_viewed & blog_id as the columns. I'm first checking whether a particular entry having the same IP and blog_id is present or not. If yes, it updates the date. Else, it inserts a new entry.
My code is below:
$search_ip = mysql_query("SELECT ip FROM viewer WHERE ip = '".$_SERVER['REMOTE_ADDR']."' AND blog_id= '".$b_id."' ");
if ($search_ip == false){
$insert_ip = mysql_query("INSERT INTO viewer (ip, blog_id, date_last_viewed) VALUES ('".$_SERVER['REMOTE_ADDR']."', '".$b_id."', NOW())");
}
else {
$update_ip = mysql_query("UPDATE viewer SET date_last_viewed = NOW() WHERE ip = '".$_SERVER['REMOTE_ADDR']."' AND blog_id='".$b_id."' ");
}
The table is not inserting anything. What am I doing wrong here? Also, as I'm new to PHP programming, could someone tell me how to modify the above code to PDO?
You can actually do it in just one query.
MySQL has a special feature called INSERT ... ON DUPLICATE KEY UPDATE which basically insert if the record does not exist or update if it already exists. One thing you need to do is to define a unique column(/s)
INSERT ... ON DUPLICATE KEY UPDATE Syntax
Based on your statement, you need to define a unique constraint on both column,
ALTER TABLE viewer ADD CONSTRAINT vw_uq UNIQUE (ip, blog_id)
and execute this statement,
INSERT INTO viewer (ip, blog_id, date_last_viewed)
VALUES ($_SERVER['REMOTE_ADDR'], b_id, NOW())
ON DUPLICATE KEY UPDATE date_last_viewed = NOW()
As a sidenote, the query is vulnerable with SQL Injection if the value(s) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.
How to prevent SQL injection in PHP?
Assuming your mysql_query executes correctly, it wont return false. What you should do is check the number of rows it returns. You can do this using mysql_num_rows.
Also, take note of the big red warning box at the top of the mysql_* man pages.
You should first add error handlers. Then move to mysqli_ and use prepared statements.
$search_ip = mysql_query( "SELECT ... " ) or die( mysql_error() );
if( mysql_num_rows($search_ip) == 0 ) {
$insert_ip = mysql_query( "INSERT ... " ) or die( mysql_error() );
}
else {
$update_ip = mysql_query( "UPDATE ... " ) or die( mysql_error() );
}
$search_ip will never == false, because it is a reference to the result. Use mysql_num_rows($earch_ip) instead. Also note that mysqli replaces this and your code is actually deprecated
That's not the right way to check if a query returned a value:
$search_ip = mysql_query("SELECT ip FROM viewer WHERE ip = '".$_SERVER['REMOTE_ADDR']."' AND blog_id= '".$b_id."' ");
if (mysql_num_rows($search_ip)==0) {
....
}

Syntax error with IF EXISTS UPDATE ELSE INSERT

I'm using MySQL 5.1 hosted at my ISP. This is my query
mysql_query("
IF EXISTS(SELECT * FROM licensing_active WHERE title_1='$title_1') THEN
BEGIN
UPDATE licensing_active SET time='$time' WHERE title_1='$title_1')
END ELSE BEGIN
INSERT INTO licensing_active(title_1) VALUES('$title_1')
END
") or die(mysql_error());
The error is
... check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF EXISTS(SELECT * FROM licensing_active WHERE title_1='Title1') THEN ' at line 1
My actual task involves
WHERE title_1='$title_1' AND title_2='$title_2' AND version='$version' ...ETC...
but I have reduced it down to make things simpler for my problem solving
In my searches on this, I keep seeing references to 'ON DUPLICATE KEY UPDATE', but don't know what to do with that.
Here is a simple and easy solution, try it.
$result = mysql_query("SELECT * FROM licensing_active WHERE title_1 ='$title_1' ");
if( mysql_num_rows($result) > 0) {
mysql_query("UPDATE licensing_active SET time = '$time' WHERE title_1 = '$title_1' ");
}
else
{
mysql_query("INSERT INTO licensing_active (title_1) VALUES ('$title_1') ");
}
Note: Though this question is from 2012, keep in mind that mysql_* functions are no longer available since PHP 7.
This should do the trick for you:
insert into
licensing_active (title_1, time)
VALUES('$title_1', '$time')
on duplicate key
update set time='$time'
This is assuming that title_1 is a unique column (enforced by the database) in your table.
The way that insert... on duplicate works is it tries to insert a new row first, but if the insert is rejected because a key stops it, it will allow you to update certain fields instead.
The syntax of your query is wrong. Checkout http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html
Use the on duplicate key syntax to achieve the result you want. See http://dev.mysql.com/doc/refman/5.0/en/insert-select.html
Another solution
$insertQuery = "INSERT INTO licensing_active (title_1) VALUES ('$title_1')";
if(!$link->query($insertQuery)){ // Insert fails, so update
$updateQuery = "UPDATE licensing_active SET time='$time' WHERE title_1='$title_1'";
$link->query($updateQuery);
}
Here is the example I tried and its works fine:
INSERT INTO user(id, name, address) VALUES(2, "Fadl", "essttt") ON DUPLICATE KEY UPDATE name = "kahn ajab", address = "Address is test"
I am amazed to see so many useless codes and answers...
Just replace INSERT with REPLACE.
¯\(ツ)/¯

Search mysql database before inserting data

I cant quite think about how to do this with mysql and php. Basically I want to be able to submit data into a mysql database but before it is inserted, it will check to see if that entry already exists.
$guid=$_POST['guid'];
$name=$_POST['name'];
//Username
$user="webhost";
//Password
$pass="*******";
//IP To Host
$ip="***********";
//Database
$db="dayz2";
//Table
$table="whitelist";
//Database Connection
$con=#mysql_connect("$ip", "$user", "$pass")
or die(mysql_error());
//Select Database
$dbcon=#mysql_select_db($db, $con)
or die(mysql_error());
$dupesql = "SELECT * FROM $table where (name = '$name' AND guid = '$guid')";
$duperaw = mysql_query($dupesql);
if (mysql_num_rows($duberaw) > 0) {
echo "Entry Already Exists";
}
else {
//Query Data Into Whitelist Table
$sql="INSERT INTO $table (name, guid) VALUES ('$name', '$guid')";
//Submit Data into Whitelist Table
$result=#mysql_query($sql, $con) or die(mysql_error());
}
?>
You can do it in another way, instead of:
submit data into a mysql database but before it is inserted, it will
check to see if that entry already exists.
You can do:
INSERT data into a mysql database if not existed, else ignore them
Something like :
INSERT IGNORE INTO table
INSERT IGNORE INTO yourtablename
SET fieldname = 'blah'
,..
It depends what you are trying to do - what is the exact criteria for your query?
You have several options:
use INSERT IGNORE ... if you only want to insert new rows that don't have a duplicate primary key. See http://dev.mysql.com/doc/refman/5.5/en/insert.html.
use INSERT ... ON DUPLICATE KEY UPDATE to insert new rows and update rows where there is a primary key match.
See http://dev.mysql.com/doc/refman/5.5/en/insert-on-duplicate.html.
use a normal SQL SELECT ... to pull the results first before performing business logic on the results before deciding which to INSERT ... or UPDATE ... depending on your requirements.
It depends how you want to handle case when the entry exists.
I you want to throw some error then you can create table trigger for insert event and put some checks there, but it will be slow because every insert will do this check.

update statement fails and no error is produced

if(isset($_POST['admin_email']))
{
$conn= mysql_connect("localhost","root","","");
mysql_select_db("qasite" ,$conn) or die(mysql_error());
$email=mysql_escape_string($_POST['admin_email']);
mysql_query(" UPDATE admin_details
SET email='$email'
WHERE admin_id=1
") or trigger_error(mysql_error(),E_USER_ERROR);
echo 'Update was successful';
}
The update statment at the end appears, but no record appears in the database. By default I set the admin_id equal 1, and no update happens. Why is that?
but no record appears in the database.
You can use UPDATE only on records that exist. If there is no record WHERE admin_id = 1, the query won't update non-existing rows.
You could use INSERT and work with the ON DUPLICATE KEY UPDATE. (then email should be an UNIQUE index).
You can change trigger_error to die(mysql_error()) and see if it works better.

Categories