Inserts about 30 times MYSQL - php

This php is supposed to insert into "d2" based on if that day is selected in "d1". It inserts about 30 times for each row in "d1". I use While all the time and never run into this problem, any idea why this would happen?
$query = mysqli_query($connection, 'SELECT * FROM '.$SETTINGS["d1"]);
while($query_array = mysqli_fetch_array($query)){
$connection_main = mysqli_connect($SETTINGS["hostname"], $SETTINGS["mysql_user"], $SETTINGS["mysql_pass"], 'u_db_main_'.$query_array['id']);
$dayofweek = strtolower(date('l'));
$query2 = mysqli_query($connection_main, 'SELECT * FROM '.$SETTINGS_MAIN["d1"].' WHERE '.$dayofweek.' ="1"');
while($query2_array = mysqli_fetch_array($query2)){
mysqli_query($connection_main, "INSERT INTO ".$SETTINGS_MAIN["d2"]." (c1) VALUE ('".$query2_array['data_1']."')");
$id = mysqli_insert_id($connection_main);
calc_function($id);
}
}
The function calc_function has NO INSERTS in it but does use a global to get the same variables, could that be recalling the insert?
function calc_function($id){
global $connection_main;
global $SETTINGS_MAIN;
//rest of function below
I have been working at this for a week and tested everything! Any help would be appreciated!

Your problem is that you are trying to use the same connection resource to both fatch and insert. As soon as you run another query on that connection you will lose the previous results. Use mysqli_fetch_all() to get all of the results from $query2, then itterate the array and run the insert query.

Related

sqlsrv_execute doesn't return anything

I'm using the SQL Server drivers for PHP to access a SQL Server database and I have a problem to update some data using sqlsrv_prpare and sqlsrv_execute functions.
I'm running two queries:
In the first query I'm retrieving some binary data (In SQL Server Management Studio, this query takes about 15 minutes to getting completed);
Then, for each row returned by the first query execution I'm trying to Update some data on the database.
Here's how my code looks like:
$query1 = "SELECT tgt.id, src.file, src.field1 from [Table1] tgt inner join [Table2] src on tgt.id = src.id order by tgt.id";
$query2 = "UPDATE [Table1] SET field1 = ? WHERE id = ?";
$getFiles = sqlsrv_query($con, $query1); //$con is the connection with the database, received by parameter
while($row = sqlsrv_fetch_array($getFiles, SQLSRV_FETCH_BOTH)) {
/* Some code here */
$file = $row[1];
$value = $row[2];
try {
if(!is_null($file)) {
$stmt = sqlsrv_prepare($con, $query2, array(&$value, &$row[0]));
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
sqlsrv_execute( $stmt );
}
} catch (Exception $e) {
error_log("\nError: " . $e->getMessage());
}
} //end while
sqlsrv_free_stmt($getFiles);
sqlsrv_close($con);
The problem is that the code inside the loop works fine to the first row, but on the second the update query isn't executed. The sqlsrv_prepare returns the value 1, but the sqlsrv_execute doesn't returns anything.
I'm thinking that the problem could be related to the first query execution time, but I don't know how to check this, considering that no error log is generated, the script just keeps executing forever.
EDIT: Actually, the example was simplified. The values that will be updated on tgt table are calculated using some data that are in src table and other application data. That's the reason why I use the loop, for each row returned by query1 specific values are calculated and used on query2. I already checked that these values are correctly calculated, this is why I thought it's better to simplify the example.
To solve this problem I have to ran the queries separately:
First I ran the query1, made the computation of the data that I needed to update the tgt table and stored them in an array;
Then, using the data stored in array, I ran the query2.
No other changes were needed.

How to declare multiple where condition for a table

hi guy's i have a question.
how to declare a multiple where clause condition inside one php only.
i have try to make my project has a minimum of a php file. i want to make my where clause inside one php file only.
this is the problem i mean. i want to put my code into one php file or inside one <?php ?>. the php code like this
<?php
include("../../Connections/koneksi.php");
$date1= $_POST['date1'];
// Data for Titik1
$sql = "SELECT * FROM termocouple where tanggal='$date1' AND silo='Silo 1'";
$query = mysqli_query($db,$sql);
$rows = array();
while($tmp= mysqli_fetch_assoc($query)) {
$rows[] = $tmp;
}
echo json_encode($rows);
mysqli_close($db);
?>
on the code above the query has select table termocouple and the filter of where condition is tanggal and silo. now the problem is i have 12 php file like that. and the different of every php is from the selecting silo, i put Silo 1,Silo 2,Silo 3, ....Silo 12.
please someone help me with this. i want to make it simple in one php file. im really appreciated when you give me an example
In order to minimize your code, if you are using the same query or code more than one time in the same project, it is more recommended to create a function, that you will call anytime you need to execute the code.
So here, since you are using the same query 12 times, you will have to create a function that executes this query, and then call this function every time you want to execute the query.
The function takes parameters, so you will have to give the function the database connection parameter $db in order to connect to the database since you are using this connection inside the function, and then you have to add the values of the where clause to the parameters also.
So your function here will take the database connection $db, $date1 fetched from $_POST, and $silo fetched from $_POST
At the end of the function, you can return any value you wish to return, so in your case, you will have to return the $rows array fetched from the query
Create a common php fileand create a function in it.
Lets say the file name is libraries.php
in this file write the following code:
<?php
function getRows($db, $date, $silo) {
$sql = "SELECT * FROM termocouple where tanggal='$date' AND silo='$silo'";
$query = mysqli_query($db, $sql);
$rows = array();
while($tmp= mysqli_fetch_assoc($query)) {
$rows[] = $tmp;
}
return json_encode($rows);
}
?>
And in each of the files where you are calling the query you will remove the php code and replace it with the following:
<?php
include("../../Connections/koneksi.php");
include("{path-to-file}/libraries.php");
$date1= $_POST['date1'];
$silo = $_POST['silo'];
$rows = getRows($db, $date1, $silo) ;
?>
I am assuming these 12 PHPs are called in diff scenarios. Why dont you pass some param from client side so that the PHP knows which scenario to execute.
$date1= $_POST['date1'];
$silo= $_POST['silo'];//This could be 'Silo 1 OR 'Silo 2' etc.
// Data for Titik1
$sql = "SELECT * FROM termocouple where tanggal='$date1' AND silo='$silo'";
$query = mysqli_query($db,$sql);

mysqli query in WHILE loop

1.) Can you nest a msqli_query inside a while loop?
2.) If yes, why would the PHP below not write any data to the precords table?
If I echo a $build array variable it shows properly, but the mysqli insert writes nothing to the table in the DB. THe code does not error out anywhere, so what am I missing about this?
$data = mysqli_query($con,"SELECT * FROM Cart WHERE Buyer_ID='$_SESSION[cid]' AND Cart_Date='$_SESSION[cdate]'");
while($build = mysqli_fetch_array($data))
{
//echo $build[idex]."<br>";
mysqli_query($con,"INSERT INTO precords (precord,Buyer_ID,Account,Purchase_Date,Item_Number,Item_Qty,Item_Title,Item_FPrice,Item_FFLFlag,ccpass) VALUES ('$build[idex]','$build[Buyer_ID]','$build[Cart_Date]','$build[Item_Number]','$build[Item_Qty]','$build[Item_Title]','$build[Item_FPrice]','$build[Item_FFLFlag]','N')");
};
Thanks for any help.
** P.S. - This code is meant to move certain values from a TEMPORARY table/session variables, over to a permanent record table, but the loop is needed since there is more than one product in the cart associated with the user/session.
yes you can use it in a loop and
you may wanna add mysql_error() function to find out what's wrong with it and try to fix it or by adding the error to the question so we can tell you what to do
$data = mysqli_query($con,"SELECT * FROM Cart WHERE Buyer_ID='$_SESSION[cid]' AND Cart_Date='$_SESSION[cdate]'");
while($build = mysqli_fetch_array($data))
{
// echo $build[idex]."<br>";
mysqli_query($con,"INSERT INTO precords(precord,Buyer_ID,Account,Purchase_Date,Item_Number,Item_Qty,Item_Title,Item_FPrice,Item_FFLFlag,ccpass)
VALUES ('$build[idex]','$build[Buyer_ID]','$build[Cart_Date]','$build[Item_Number]','$build[Item_Qty]','$build[Item_Title]','$build[Item_FPrice]','$build[Item_FFLFlag]','N')")
or die (mysql_error());
};
in a simplified form when you want to fetch data from a database to display in html list I intentionally added mysqli ORDER BY which have only two order ASC[ascending] and DESC[descending] and I also used mysqli LIMIT which i set to 3 meaning that number of result fetch from the database should be three rows only
I concur with the answer of ali alomoulim
https://stackoverflow.com/users/2572853/ali-almoullim
MY SIMPLIFIED CODE FOR THE LOOPING WHILE MYSQLI ORDER BY AND LIMIT
$usersQuery = "SELECT * FROM account ORDER BY acc_id DESC LIMIT 3";
$usersResult=mysqli_query($connect,$usersQuery);
while($rowUser = mysqli_fetch_array($usersResult)){
echo $rowUser["acc_fullname"];
}

php request of mysql query timeout

i'm trying to make a long mysql query and process and update the row founded:
$query = 'SELECT tvshows.id_show, tvshows.actors FROM tvshows where tvshows.actors is not NULL';
$result = mysql_query($query);
$total = mysql_num_rows($result);
echo $total;
while ($db_row = mysql_fetch_assoc($result))
{
//process row
}
but after 60 second give me a timeout request, i have try to insert these in my php code:
set_time_limit(400);
but it's the same, how i can do?
EDIT:
only the query:
$query = 'SELECT tvshows.id_show, tvshows.actors FROM tvshows where tvshows.actors is not NULL';
takes 2-3 second to perform, so i think the problem is when in php i iterate all the result to insert to row or update it, so i think the problem is in the php, how i can change the timeout?
EDIT:
here is the complete code, i don't think is a problem here in the code...
$query = 'SELECT tvshows.id_show, tvshows.actors FROM tvshows where tvshows.actors is not NULL';
$result = mysql_query($query);
$total = mysql_num_rows($result);
echo $total;
while ($db_row = mysql_fetch_assoc($result)) {
//print $db_row['id_show']."-".$db_row['actors']."<BR>";
$explode = explode("|", $db_row['actors']);
foreach ($explode as $value) {
if ($value != "") {
$checkactor = mysql_query(sprintf("SELECT id_actor,name FROM actors WHERE name = '%s'",mysql_real_escape_string($value))) or die(mysql_error());
if (mysql_num_rows($checkactor) != 0) {
$actorrow = mysql_fetch_row($checkactor);
$checkrole = mysql_query(sprintf("SELECT id_show,id_actor FROM actor_role WHERE id_show = %d AND id_actor = %d",$db_row['id_show'],$actorrow[0])) or die(mysql_error());
if (mysql_num_rows($checkrole) == 0) {
$insertactorrole = mysql_query(sprintf("INSERT INTO actor_role (id_show, id_actor) VALUES (%d, %d)",$db_row['id_show'],$actorrow[0])) or die(mysql_error());
}
} else {
$insertactor = mysql_query(sprintf("INSERT INTO actors (name) VALUES ('%s')",mysql_real_escape_string($value))) or die(mysql_error());
$insertactorrole = mysql_query(sprintf("INSERT INTO actor_role (id_show, id_actor, role) VALUES (%d, %d,'')",$db_row['id_show'],mysql_insert_id())) or die(mysql_error());
}
}
}
}
Should definitely try what #rid suggested, and to execute the query on the server and see the results/duration to debug - if the query is not a simple one, construct it as you would in your PHP script, and only echo the SQL command, don't have to execute it, and just copy that in to the server MySQL command line or whichever tool you use.
If you have shell access, use the top command after running the above script again, and see if the MySQL demon server is spiking in resources to see if it really is the cause.
Can you also try a simpler query in place of the longer one? Like just a simple SELECT count(*) FROM tvshows and see if that also takes a long time to return a value?
Hope these suggestions help.
There are so many problems with your code.
Don't store multiple values in a single column. Your actors column is pipe-delimited text. This is a big no-no.
Use JOINs instead of additional queries. You can (or could, if the above weren't true) get all of this data in a single query.
All of your code can be done in a single query on the server. As I see it, it takes no input from the user and produces no output. It just updates a table. Why do this in PHP? Learn about INSERT...SELECT....
Here are some resources to get you started (from Googling, but hopefully they'll be good enough):
http://www.sitepoint.com/understanding-sql-joins-mysql-database/
http://dev.mysql.com/doc/refman/5.1/en/join.html
http://dev.mysql.com/doc/refman/5.1/en/insert-select.html
What is Normalisation (or Normalization)?
Let me know if you have any further questions.

How to make loop

This would helps me a lot to understand how does loop works
Let say i've database table my_table (id,words) and here is example of database
INSERT INTO `my_table` VALUES (1,'hello manal');
INSERT INTO `my_table` VALUES (2,'nice manal');
INSERT INTO `my_table` VALUES (3,'pretty manal');
now imagine for 100,000 entries (huge) and i want to replce the word manal to jack and giving me results every line changed one by one
i'll use
$conn = mysql_connect('localhost','USER','PASS') or die(mysql_error());
mysql_select_db('my_table',$conn);
$sql = "SELECT * from my_table";
$result = mysql_query($sql,$conn);
while ($row = mysql_fetch_array($result)){
$old = $row['words'];
$id = $row['id'];
$new="jack";
$new = str_replace("manal", "$new", $old);
echo $new;
}
The loop
by that code it will works all at once which is impossible to my hosting server to apply all so i want to make it as loop ! i mean it will change the 1st database line then gives me the results echo $new; then change the 2nd database line then gives the results echo $new; and so on with no stop till last line.
so my important part is getting the results one by one ~thanks
The problem will be that your output is being buffered which is why you see all the results at the same time (at the end of the execution of the script).
You could add ob_flush(); flush(); within the loop before echo $new; an see if that helps. Regardless, the above example is going to execute pretty quickly so it isn't exactly going to be easily readable!
You better do this replace in the database itself and then you just print it out.
$sql = "UPDATE my_table SET words = REPLACE(words, 'manal', 'jack')";

Categories