How to add dynamic counter for insert sql - php

I would like to add a counter to show sequence of record inserted per query.
if(isset($_POST['keyword'])){
$keyword = $_POST['keyword'];
if($keyword){
foreach($keyword as $row){
$keyword_exe = $con->prepare("
INSERT INTO t_theme(m_id,keyword,sequence_counter)VALUES('$id','$row', '???')
");
$keyword_exe->execute();
}
}
}
I expect the output will be like this:

I didnt test with INSERT but you can use this when you SELECT
ROW_NUMBER() OVER(PARTITION BY m_id ORDER BY id ASC) sequence_counter
For save some database space
More here

$counter = 0;
$pre_row = 0;
foreach($keyword as $row){
if( $pre_row == $id){
//In row m_id value equal to next value increase counter by 1
$counter++;
}else{
//else start to 1
$counter = 1;
$pre_row = $id;
}
$keyword_exe = $con->prepare("
INSERT INTO t_theme(m_id,keyword,sequence_counter)VALUES('$id','$row', '$counter')
");
$keyword_exe->execute();
}
DEMO

Related

how to update column without using auto_increment value with 001 to so on

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)

PHP Insert multiple rows in split batches

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.=",";
}
}

PHP loop stops unexpectly

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

PHP MySql Swap value in two rows

I've seen a couple variations on this, but mainly they swap the entire row rather than just one value in that row, and not dynamically.
Here's the issue:
I have three rows each with the following cells (id, title, content, display_order, visible).
id is auto_increment. title and content are manually entered and visible is a toggle. display_order is set when each row is created and automatically set as the highest integer and set at the bottom of the stack.
I set it like this so that if any of these records were to be manually deleted, i can reorder the stack automatically (if there are 4 records, and I delete #2, the new order resets as 1,2,3 and not 1,3,4).
Each row has a set of up and down arrow buttons that call move.php with queries of id(id), display_order(pos) and direction(dir).
In the move.php it uses a conditional to determine whether to move the record UP or DOWN depending on what the direction variable is set at.
What PHP code do I need to write to take these three variables (id, pos, dir) and swap the value in the table cell display_order: Here's a visual representation
Initial:
id title pos
-----------------
1 slide1 1
2 slide2 2
3 slide3 3
After I click the UP button for record ID #3:
id title pos
-----------------
1 slide1 1
2 slide2 3
3 slide3 2
MIND YOU the ID and POS will not always be the same integer
USING davidethell's suggestion I have created this:
Here's what I have created, but all I'm getting is the echo $newPos rather that is going back to the admin.php:
require ("connection.php");
$id = $_GET['id'];
$pos = $_GET['pos'];
$dir = $_GET['dir'];
if ($dir == 'up') {
$newPos = $pos-1;
} else {
$newPos = $pos+1;
}
$fromRow = "SELECT * FROM pages WHERE display_order = ".$pos."";
$toRow = "SELECT * FROM pages WHERE display_order = ".$newPos."";
$reord = mysqli_query($conn, "UPDATE pages SET display_order = " . $toRow['display_order'] . " WHERE id = " . $fromRow['id']."; UPDATE pages SET display_order = " . $fromRow['display_order'] . " WHERE id = " . $toRow['id']);
if ($reord){
header("Location: admin.php");
}else{
echo $newPos;
}
The problem I'm running into is that it only echos the $newPos
UPDATED CODE:
require ("connection.php");
$fromArray = array();
$toArray = array();
$id = $_GET['id'];
$pos = $_GET['pos'];
$dir = $_GET['dir'];
if ($dir == 'up') {
$newPos = $pos-1;
} else {
$newPos = $pos+1;
}
$fromRow = mysql_query("SELECT * FROM pages WHERE display_order = ".$pos."");
$toRow = mysql_query("SELECT * FROM pages WHERE display_order = ".$newPos."");
$reord = mysqli_query($conn, "UPDATE pages SET display_order = " . $toRow['display_order'] . " WHERE id = " . $fromRow['id']);
$reord = mysqli_query($conn, "UPDATE pages SET display_order = " . $fromRow['display_order'] . " WHERE id = " . $toRow['id']);
if ($reord){
header("Location: admin.php");
}else{
echo $newPos;
}
Result: echos the $newPos instead of return to admin.php
You could use this query:
UPDATE
yourtable INNER JOIN (
SELECT
MAX(yourtable.pos) pos_prec,
curr.pos pos_curr
FROM
yourtable INNER JOIN
(SELECT pos FROM yourtable WHERE id=3) curr
ON yourtable.pos<curr.pos
GROUP BY
curr.pos) cp ON yourtable.pos IN (cp.pos_prec, cp.pos_curr)
SET
pos = CASE WHEN pos=cp.pos_curr
THEN pos_prec ELSE pos_curr END
It's a little bit complicated, but it will swap the value of the position where ID=3 with the value of the position of the preceding item, even if there are gaps.
Please see fiddle here.
EDIT
If there are no gaps, you could simply use this to move ID#3 UP:
UPDATE
yourtable INNER JOIN (SELECT pos FROM yourtable WHERE id=3) curr
ON yourtable.pos IN (curr.pos, curr.pos-1)
SET
yourtable.pos = CASE WHEN yourtable.pos=curr.pos
THEN curr.pos-1 ELSE curr.pos END;
and just use +1 instead of -1 to move down (both UP and DOWN can be combined in one single query if needed).
PHP Code
And this is using PHP and mysqli, and assuming that the position is given:
<?php
$mysqli = new mysqli("localhost", "username", "password", "test");
$pos = 3;
$dir = 'down';
if ($dir == 'up') { $newPos = $pos-1; } else { $newPos = $pos+1; }
if ($stmt = $mysqli->prepare("
UPDATE
yourtable
SET
pos = CASE WHEN yourtable.pos=?
THEN ?
ELSE ? END
WHERE
pos IN (?, ?)
AND (SELECT * FROM (
SELECT COUNT(*) FROM yourtable WHERE pos IN (?,?)) s )=2;"))
{
$stmt->bind_param("iiiiiii", $pos, $newPos, $pos, $pos, $newPos, $pos, $newPos);
$stmt->execute();
printf("%d Row affected.\n", $stmt->affected_rows);
$stmt->close();
}
$mysqli->close();
?>
(i also added a check, if trying to move UP the first pos, or DOWN the last one it will do nothing).
Assuming a $row object with each row data, just do:
if ($dir == 'up') {
$fromRow = $row2;
$toRow = $row1;
}
else {
$fromRow = $row1;
$toRow = $row2;
}
$sql = "UPDATE mytable SET pos = " . $toRow['pos'] . " WHERE id = " . $fromRow['id'];
// now execute your SQL however you want in your framework
$sql = "UPDATE mytable SET pos = " . $fromRow['pos'] . " WHERE id = " . $toRow['id'];
// now execute your SQL however you want in your framework
Put that in a function or class of some kind to make it reusable.
EDIT:
Based on your edits it looks like you are not fetching enough information in your queries. They should be:
$fromRow = mysql_query("SELECT * FROM pages WHERE display_order = ".$pos."");
$toRow = mysql_query("SELECT * FROM pages WHERE display_order = ".$newPos."");
You were only selecting the id field, but then you were trying to use the display_order field.
i will not write you the PHP code. But i will give you the SQL:
Let's say $delta is either +1 if the slide's position should be raised 1, or -1 if the slide's position should be lowered by 1.
$id is the id of the slide. Ow, and let's assume the table is called slides_table.
You will need 2 queries:
update slides_table set pos = pos + $delta where id = $id;
update slides_table set pos = pos - $delta where pos = (select pos from slides_table where id=$id) and id != $id

select with limit and update table. Limit not working fine. sql

I am trying to update thable with select using limit
It's update table fine when we enter "limit" only with one parameter in select query like (limit 50)
But when select with "limit" like (limit $sqlFrom, $sqlTo) it updates the table but skip 2nd (51 to 100) records and again start updating from 101.
It skip every 2nd 50 records
Where is the problem???
Here is the code
$sqlFrom = 0;
$sqlTo = 50;
for($try = 0; $try < 6; $try++)
{
$res = mysql_query("select * from table_name where underprocess = 0 limit " . $sqlFrom . "," . $sqlTo);
while($row = mysql_fetch_array($res))
{
$id = $row['id'];
mysql_query("update table_name set underprocess = 1 where id = " . $id) or die('error');
echo $id;
}
print '<hr/>';
if($sqlFrom != 0)
{
$sqlFrom += $sqlTo;
}
else
{
$sqlFrom = $sqlTo;
}
}//for
This is as expected
When you update rows 1-50 based on your first iteration, you set underprocess = 1. These are ignored in the 2nd call because ask for rows underprocess = 0.
So rows 51-100 in the 1st query are now rows 1-50 for your 2nd query if you like.
You don't need to change your LIMIT range because you always want the "first" 50.
NOTE
Your LIMIT isn't guaranteed anyway because you have no ORDER BY.

Categories