I have a query to insert multiple rows in split batches. Basically, I need to split inserts in batches so that I can generate a unique random ID to the inserted batch.
What I've tried and failed with many different options, one of them as follow.
$batch = 150;
$sql = "SELECT DISTINCT `column` FROM `table` GROUP BY `column` ORDER BY `ID` ASC";
$sqle = $con->Execute($sql);
$results = $sqle->getrows();
for($i=0; $i<count($results);$i++){
$columns1 = $results[$i]['column'];
if($i==$batch){
$randd = randcode(5).time();
$sql = "INSERT INTO `newtable` SET `columns1` = ".$con->qstr($columns1).", `rcode` = ".$con->qstr($randd).", `DATE_PUBLISHED` = ".$con->qstr($sdate);
$results=$con->Execute($sql);
$i=0;
}
}
However, am not successful in inserting unique code to every 150 batch inserted query.
Where am I going wrong in generating random unique code for every batch? And also I would like to know if there is less than 150 records, then how to handle the same?
This will provide you with the logic for a basic way for setting a random ID per batch.
In this example, there is no database connectivity. You will have to add that yourself. You also want to have a look at the syntax for the INSERT statement (spoiler: INSERT INTO <table name> (<columns>) VALUES (<values>)).
// For this example, generate a result array with 350 rows
// (remove when using actual db query)
for ($i = 1; $i <= 350; $i++) {
$results[] = ['column' => 'column ' . $i];
}
// Loop through all result rows
foreach ($results as $batchCounter => $result) {
if ($batchCounter % 150 == 0) {
// Generate a new random ID for the first row and every 150 rows
$random = uniqid();
}
// Replace with proper insert statement
echo "Insert random ", $random, ' for column "', $result['column'], '"', PHP_EOL;
}
Output:
Insert random 55e0186b0607f for column "column 1"
Insert random 55e0186b0607f for column "column 2"
Insert random 55e0186b0607f for column "column 3"
...
Insert random 55e0186b0607f for column "column 150"
Insert random 55e0186b063da for column "column 151"
Insert random 55e0186b063da for column "column 152"
Insert random 55e0186b063da for column "column 153"
...
Insert random 55e0186b063da for column "column 300"
Insert random 55e0186b0666e for column "column 301"
Insert random 55e0186b0666e for column "column 302"
Insert random 55e0186b0666e for column "column 303"
...
Insert random 55e0186b0666e for column "column 350"
You have to try this one
<?php
$batch = 0;
$sql = "SELECT DISTINCT `column` FROM `table` GROUP BY `column` ORDER BY `ID` ASC";
$sqle = $con->Execute($sql);
$results = $sqle->getrows();
$sql = "";
for($i=0; $i<count($results);$i++)
{
$columns1 = $results[$i]['column'];
$randd = randcode(5).time();
if($batch==0)
{
$sql = "insert into `demo` (`columns1`, `rcode`, `DATE_PUBLISHED`) values "
}
$sql.= "(".$results[$i]['column1'].",".$randd.",".$results[$i]['column1']."),";
if($batch==150)
{
$results=$con->Execute($sql);
$batch=0;
$sql="";
}
$batch++;
}
You have to try this one. I fixed some errors from your code to insert records successfully:
<?php
$batch = 1;
$rows = 0;
$sql = "";
$sql = "SELECT DISTINCT `column` FROM `table` GROUP BY `column` ORDER BY `ID` ASC";
$sqle = $con->Execute($sql);
$results = $sqle->getrows();
for($i=0; $i<count($results);$i++)
{
$columns1 = $results[$i]['column'];
$randd = randcode(5).time();
if($batch==1)
{
$sql = "insert into `demo` (`columns1`, `rcode`, `DATE_PUBLISHED`) values "
}
$sql.= "(".$results[$i]['column1'].",".$randd.",".$results[$i]['column1']."),";
$rows++;
if($batch==100)
{
$this->SendRecords($conn, $sql);
$batch=1;
$sql="";
} else if($rows == count($results) && $batch > 1 && $batch<=100){
$this->SendRecords($conn, $sql);
$batch=0;
$sql="";
}else {
$batch++;
$sql.=",";
}
}
Related
Hello I want to run two queries in this code. The first delets a row in the mysql table and the second reorders the id value to the right sequence.
if(isset($_POST["image_id"]))
{
$file_path = 'files/' . $_POST["image_name"];
if(unlink($file_path))
{
$count= 0;
$count++;
$query1 = "DELETE FROM tbl_image WHERE image_id = '".$_POST["image_id"]."'";
$query2 = "UPDATE 'tbl_image' SET 'image_id' = '$count' " ;
$statement = $connect->prepare($query1, $query2);
$statement->execute();
}
}
This is my table with name and unique numberenter image description here
This is my PHP code
$id = explode(",", $params["txtID"]);
for ($i = 0; $i <count($id); $i++) {
$sql = "SELECT 'auto_increment' as LastID FROM
INFORMATION_SCHEMA.TABLES WHERE table_name = 'esi_master' ";
$result = $this->con->query($sql);
if (intval($result->rowCount($result)) > 0) {
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
$lclId = intval($row["LastID"]) - 1 + intval('1');
$lclDcno = '00'.$lclId ;
echo $row["LastID"];
}
} else {
$lclId = intval($row["LastID"]) + intval('1');
$lclDcno = '00'.$lclId ;
echo $row["LastID"];
}
$sql = $this->con->prepare("UPDATE esi_master SET esi_status = 1,
esi_dcno = '$lclDcno[$i]' Where esi_id = '$id[$i]'");
echo $result = $sql->execute();
}
Here First I insert Names to the table using Insert Statements and next for some operation I update the Unique number unique number should start updating from the empty row, update done with unique id, The txtID contains ID`s like 1, 2, 3, 4 so on as I select table row in front end, in that basis that updates.Thanks in Advance.
You need another field to save, with type varchar(10).
data will not be able to save into integer(auto_increment)
I have a table (table3) in MYSQL with 99 text fields (field1, filed2, ...,field99). I wanted to count the non-empty values of each field so I wrote a simple php script with a for loop as below:
for($i = 1; $i <= 99; $i++)
{
$sqlstm = "SELECT COUNT(field$i) FROM table3 WHERE field$i IS NOT NULL AND field$i <> '';";
$r = #mysqli_query($dbc, $sqlstm);
if($r)
{
while($row = #mysqli_fetch_array($r))
{
echo "<p>$row[0]</p>\n";
}
}
else
{
echo "field $i error: " . mysqli_error($dbc);
}
}
But the loop stopped after showing four values (field1 to filed4) and no error message. I do have all 99 fields with data in table3 and I could run the query manually for any field. Could this due to browser timeout?
Can someone help me? Thanks.
$sqlstm = "SELECT COUNT(field$i) FROM table3
you are selecting the columns here, your table has 99 rows but apperantly only 4 columns
what you could better do is
$sqlstm = "SELECT * FROM table3 WHERE (column name) IS NOT NULL";
$count = 0
for($sqlstm as $one) {
$count = $count + 1;
}
echo($count);
or something along those lines
I have
$result = "";
if(someCondition)
$result = mysql_query("SELECT * FROM table1 WHERE column = '$value' ");
else
$result = mysql_query("SELECT * FROM table2 WHERE column = '$value' ");
$result could have 0 -> infinity rows returned
Table 1 and Table 2 have different amounts of columns with different names
I want to write 1 generic loop after the above else that will just print out all of the rows. Preferably 1 per line or deliminated.
To clarify, one of the two query calls will fill the $results variable with rows.
I wont know which one fills it at run time so I want to just do a print all contents to screen. Is there a method that does this? is there a fast loop that iterates through all of the rows without explicitly saying the column names?
bored enough to answer:
$result = "";
if(someCondition){
$result = mysql_query("SELECT * FROM table1 WHERE column = '$value' ");
}else{
$result = mysql_query("SELECT * FROM table2 WHERE column = '$value' ");
}
while ($row = mysql_fetch_array($result)) ) {
foreach($row as $key => $var)
{
echo $key . ' = ' . $var . '<br />';
}
}
I was wondering if there was an easy way to do this:
I have a user_id column and then 33 other columns with either a '0' or a '1' as the type. How can I easily select all of the columns where the user_id = 320 and the column's data equals 1?
The column titles are labeled 1-33. In the end I want to join it to another table where 1-33 is the id to a label column.
Does this make sense?
Thanks for any help!
Try this I get all the fields and test if it BIT and then inject it to the query
And please tell me the result
<?php
$result = mysql_query("SHOW COLUMNS FROM sometable");
if (!$result){
echo 'Could not run query: ' . mysql_error();
exit;
}
if (mysql_num_rows($result) > 0){
$str ="";
$nums = mysql_num_rows($result);
$i = 0 ;
while ($row = mysql_fetch_assoc($result)){
$i++;
if($row['Type'] = 'BIT' && $i != $nums){
$str .= " WHERE `".$row['Field']."` = 1 AND";
}
elseif($row['Type'] = 'BIT' && $i == $nums){
$str .= " WHERE `".$row['Field']."` = 1 ";
}
}
}
$query = "SELECT * FROM mytable user_id = 320 AND ".$str;
$q = mysql_query($query);
This is for the first part of you question
the second part the same operation
and this working without knowing the fields name