Avoid multiple Insertion, when insert query called multiple times at same time - php

$Link= mysql_connect("localhost", "root", "", "");
query = mysql_query($Link,"SELECT col_name FROM table_name WHERE col_name='$val'");
$num=mysql_num_rows($query);
if($num==0){
$query1 = mysql_query($Link,"INSERT INTO table_name(col_name)VALUES('$val')"); )
}
There will be multiple calls to query at same time. I used this method to avoid multiple insertion, but sometimes multiple rows are inserted.Please help me. Thanks in advance.
thanks for your help..
I m not calling this code in loop but multiple calls at same time from different users are made.

mysql_query syntax: resource mysql_query ( string $query [, resource $link_identifier = NULL ] )
$query1 = mysql_query("INSERT INTO table_name (col_name)VALUES('".$val."')");
Full code:
$Link= mysql_connect("localhost", "root", "", "");
$query = mysql_query($Link,"SELECT col_name FROM table_name WHERE col_name='".$val."'");
$num=mysql_num_rows($query);
if($num==0){
$query1 = mysql_query("INSERT INTO table_name(col_name)VALUES('".$val."')");
}

If there are multiple simultaneous requests to the web server(s) that host the PHP, the select could return no results for more than one of these requests, and then there may be multiple inserts due to each such request performing the insert.
If you are not running windows and have only one web server, you could synchronize access to this code using PHP's semaphores.
But even better, can you put a unique constraint on the value of this column in the table in mysql?

Though your code is correct and it should not insert again, but
You should add a unique key to your field and then use Insert Ignore
"INSERT IGNORE INTO table_name(col_name)VALUES('$val')"

Related

Use mysql_insert_id in single query

Ok, don't know if this is simple in practice as it is in theory but I want to know.
I have a single INSERT query were by in that query, i want to extract the AUTO_INCREMENT value then reuse it in the same query.
For example
//values to be inserted in database table
$a_name = $mysqli->real_escape_string($_POST['a_name']);
$details = $mysqli->real_escape_string($_POST['details']);
$display_type = $mysqli->real_escape_string($_POST['display_type']);
$getId = mysqli_insert_id();
//MySqli Insert Query
$insert_row = $mysqli->query("INSERT INTO articles (a_name,details,display_type,date_posted) VALUES('$a_name','$details','$display_type$getId',CURRENT_TIMESTAMP)");
Apparently, am getting a blank value(I know because the mysqli_insert_id() is before the query, but I've tried all i could but nothing has come out as i want. Can some please help me on how to achive this
From my knoweldge this cant be done. Because no query has been run, MySQL is unable to return the ID of said query.
You could use a classic approach, pull the id of the previous record and add 1 to it, this is not a great solution as if a record is deleted, the auto increment value and the last value +1 may differ.
Run multiple queries and then use the insert_id (MySQLi is different to what you are using, you are best using $db->lastInsertId(); as mentioned in the comments.
Run a query before hand and store it as a variable;
SELECT auto_increment FROM INFORMATION_SCHEMA.TABLES WHERE table_name = 'tablename'
I strongly recommend Option 2, it is simply the cleanest and most reliable method for what you are looking to achieve.
It seems the value required for $display_type is :$display_type + (max(id) + 1).
In order to get the max_id you'll have to do this query before :
$sql = "SELECT id FROM articles ORDER BY id DESC LIMIT 1";
$result = mysqli->query($sql);
$maxid = $result->fetch_array(MYSQLI_NUM);
// $maxid[0] will contains the value desired
// Remove the mysqli_insert_id() call - Swap $getid by ($maxid[0] + 1)
// and u're good to go
N.B. update the name of ur primary key in the query $sql.
EDIT :
Assuming the weakness of the query and the quick resarch i did.
Try to replace $sql by (don't forget to Update DatabaseName & TableName values) :
$sql = SELECT `AUTO_INCREMENT`
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'DatabaseName'
AND TABLE_NAME = 'TableName';
That Should do it . More info on the link below :
Stackoverflow : get auto-inc value
I don't think this can be done. You'll have to first insert the row, then update display_type, in two separate queries.
Thanks guys for your opinions, out of final copy, paste, edit and fix; here is the final working code(solution)
`
//values to be inserted in database table
$a_name = $mysqli->real_escape_string($_POST['a_name']);
$details = $mysqli->real_escape_string($_POST['details']);
$display_type = $mysqli->real_escape_string($_POST['display_type']);
//Select AUTO_INCREMENT VALUE
$sql = "SELECT `AUTO_INCREMENT`
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'chisel_bk'
AND TABLE_NAME = 'articles'";
$result = $mysqli->query($sql);
$maxid = $result->fetch_array(MYSQLI_NUM);
$getId = $maxid[0];
//MySqli Insert Query
$insert_row = $mysqli->query("INSERT INTO articles (a_name,details,display_type,date_posted) VALUES('$a_name','$details','$display_type$getId',CURRENT_TIMESTAMP)");
This happens to do the magic!!!
`

How to check with PHP does a SQL database already have

I've tried to find the answer to this question but none of the answers fit.
I have two databases, one has 15.000.000 entries and I want to extract the necessary data and store it in a much smaller database with around 33.000 entries. Both databases are open at the same time. Or at least they should be.
While having the big database open and extracting the entries from it, is it possible to check whether the value already exists in a certain table in the smaller database? I just need some generic way which checks that.
In my code I'm first opening both databases (big one is oddsnavi_push, small one is oddsnavi_baby):
$database = "oddsnavi_push";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
$database_baby = "oddsnavi_baby";
$db_handle_baby = mysql_connect($server, $user_name, $password);
$db_found_baby = mysql_select_db($database_baby, $db_handle_baby);
And then I'm starting to read and calculate data from oddsnavi_push:
$SQL_SELECT_ALL = "...giant query...";
$result_select_all = mysql_query( $SQL_SELECT_ALL );
while($db_field_all = mysql_fetch_assoc( $result_select_all ) ) {
$SQL_INSERT="INSERT INTO oddsnavi_baby.calc (id, one, two) VALUES ('$id', '$one', '$two')";
It works up until that point. It takes the data which was read (id, one, two) and inserts them in proper columns in oddsnavi_baby table named calc. It does that properly when the oddsnavi_baby is completely empty.
However, I need it to only update the database IF an entry (based on whether a certain 'id' exists or not) doesn't exist.
EDIT: I will rephrase my question. From the query results (big database) I'm getting strings, for every row. For example $string. How do I open the second database and check if oddsnavi_baby.calc table has the $string value in column Events?
Skip the check and try with just INSERT IGNORE assuming the Id is a unique key.
http://dev.mysql.com/doc/refman/5.5/en/insert.html
Man, I remember coming up against a problem like this once. I think we actually went the slow, expensive route and wrote a script to pull one entry at a time, compare it, and insert it if it didn't already exist.
However, I found this post, which sounds like it might be of some help to you:
http://www.mysqlfaqs.net/mysql-faqs/Tricky-Select-Queries/How-to-compare-data-of-two-tables-of-two-different-databases-in-MySQL
Good luck :)
Why do you really need multiple database? Amount does not matter tables are just fine, no need to split.
//Multiple links to different databases
$dblink1 = mysqli_connect($localhost, $user, $pass, $db1);
$dblink2 = mysqli_connect($localhost, $user, $pass, $db2);
$id = '1'; // Id to check
$query = "SELECT COUNT(*) FROM `table` WHERE id = '1' LIMIT 1";
$result = mysqli_query($dblink1, $query); //query db 1
if(mysql_num_rows($result)) {
$query = "INSERT INTO `table` VALUES(.....)";
$result = mysqli_query($dblink1, $query); //query db 2
}

mysql_query returns nulls

I've got a php script which queries mysql for a certain row based on it's id.
This works fine for the first 3 rows , but on the 4th it returns nulls on all fields.
Here's the query:
mysql_query("SELECT ind,title,body,img,tags,live FROM project WHERE ind = '".$curid."' ")
let me know if you need to see more code.
I'm going to take a guess that the forth row doesn't have the id you think it does. Return them all (remove the where statement) and output them to the screen to check, or use a database browsing tool, if you have one.
Try some debugging..
$q = "SELECT ind,title,body,img,tags,live FROM project WHERE ind = '".$curid."' ";
$rs = mysql_query($q) or die("MySQL error in Query: ". $q ."<br><br>The error is:<br>".mysql_error());
when you execute query, change $curid by value that you consider is correct. verify result, if yet get null values, you can do it:
mysql_query("SELECT ind,title,body,img,tags,live FROM project WHERE ind = '".$curid."' " and
ind IS NOT NULL and title IS NOT NULL
)
for example

mysqli_multi_query function not updating all table rows in database

I have been attempting to use mysqli_multi_query to update multiple table rows at once. I have found that this function always leads to the update of all rows except for 1 row. For instance, if I had 5 rows of data that I designated to be updated, then only 4 rows are actually updated. Even when I increased the numbers of rows to 6 or 7 etc, there is only 'n-1' rows actually updated ('n' being the numbers that I designated to be updated).
some of the code is below:
<?php $jag = mysqli_connect($host, $user, $pass, $db); // connects to the database
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query2 .= "UPDATE inst_prod_stor SET age_type = '2' WHERE payer_mail = '$pmail' AND file_name = '$fname';";
print_r($query2);
// execute the 'update' multi query
$result2 = mysqli_multi_query($jag, $query2) or die(mysqli_error($jag));
mysqli_close($jag); ?>
I have also checked the source code on my webpage after I execute the php file that cotains this code and it is fine. I receive no errors. I actually used the 'print_r' function to check that no data was being left out before the 'mysqli_multi_query' function executed. And in fact, no data was left out. The result of the function is almost perfect every single time I execute the code. The only imperfection is the fact that one row of the table is never of updated. And each time it's a different row.
I really need help on this one, it is pretty much the last leg of a 2 or 3 week coding journey before I finish up a project that I am currently working on. Thanks!
use mysql_real_escape_string and remove . near $query2
$pmail = mysql_real_escape_string($pmail);
$fname= mysql_real_escape_string($fname);
$query2 = "UPDATE inst_prod_stor SET age_type = '2' WHERE payer_mail = '$pmail' AND file_name = '$fname';";
$result2 = mysqli_multi_query($jag, $query2) or die(mysqli_error($jag));
will only die() if the first query in $query2 has an error.
I suggest that you use a do-while loop to establish a means to debug non-first query sql failures using mysqli_error() & mysqli_affected_rows().
Strict Standards: mysqli_next_result() error with mysqli_multi_query

How to connect to 2 databases at the same time in PHP

I am trying to connect to 2 databases on the same instance of MySQL from 1 PHP script.
At the moment the only way I've figured out is to connect to both databases with a different user for each.
I am using this in a migration script where I am grabbing data from the original database and inserting it into the new one, so I am looping through large lists of results.
Connecting to 1 database and then trying to initiate a second connection with the same user just changes the current database to the new one.
Any other ideas?
You'll need to pass a boolean true as the optional fourth argument to mysql_connect(). See PHP's mysql_connect() documentation for more info.
If your database user has access to both databases and they are on the same server, you can use one connection and just specify the database you want to work with before the table name. Example:
SELECT column
FROM database.table
Depending on what you need to do, you might be able to do an INSERT INTO and save a bunch of processing time.
INSERT INTO database1.table (column)
SELECT database2.table.column
FROM database2.table
Lucas is correct. I assume that both the databases are hosted on the same host.
Alternatively, you can create only 1 db connection and keep swapping the databases as required. Here is pseudo code.
$db_conn = connect_db(host, user, pwd);
mysql_select_db('existing_db', $db_conn);
-- do selects and scrub data --
mysql_select_db('new_db', $db_conn);
-- insert the required data --
I would suggest using two connection handlers
$old = mysql_connect('old.database.com', 'user', 'pass);
mysql_select_db('old_db', $old);
$new = mysql_connect('new.database.com','user','pass);
mysql_select_db('new_db', $new)
// run select query on $old
// run matching insert query on $new
If it's an option, use PDO: you can have as many database connections open as you like.
Plus, assuming your executing the same queries over and over, you can use prepared statements.
You can easily use 2 databases in same time with following Codes:
<?php
define('HOST', "YOURHOSTNAME");
define('USER', "YOURHOSTNAME");
define('PASS', "YOURHOSTNAME");
define('DATABASE1', "NAMEOFDATABASE1");
define('DATABASE2', "NAMEOFDATABASE2");
$DATABASE1 = mysqli_connect(HOST, USER, PASS, DATABASE1);
$DATABASE2 = mysqli_connect(HOST, USER, PASS, DATABASE2);
if(!$DATABASE1){
die("DATABASE1 CONNECTION ERROR: ".mysqli_connect_error());
}
if(!$DATABASE2){
die("DATABASE2 CONNECTION ERROR: ".mysqli_connect_error());
}
$sql = "SELECT * FROM TABLE"; /* You can use your own query */
$DATABASE1_QUERY = mysqli_query($DATABASE1, $sql);
$DATABASE2_QUERY = mysqli_query($DATABASE2, $sql);
$DATABASE1_RESULT = mysqli_fetch_assoc($DATABASE1_QUERY);
$DATABASE2_RESULT = mysqli_fetch_assoc($DATABASE2_QUERY);
/* SHOW YOUR RESULT HERE WHICH DATABASE YOU WANT FROM */
echo $DATABASE1_RESULT['id'];
echo $DATABASE2_RESULT['id'];
/*After complete your all work don't forgot about close database connections*/
mysqli_close($DATABASE1);
mysqli_close($DATABASE2);
?>
First Connect Two Database
$database1 = mysql_connect("localhost","root","password");
$database2 = mysql_connect("localhost","root","password");
Now Select The Database
$database1_select = mysql_select_db("db_name_1") or die("Can't Connect To Database",$database1);
$database_select = mysql_select_db("db_name_2") or die("Can't Connect To Database",$database2);
Now if we want to run query then specify database Name at the end like,
$select = mysql_query("SELECT * FROM table_name",$database1);

Categories