PHP MySql Swap value in two rows - php

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

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 - Order a list of database elements

I am displaying a list of items based on a database. The order of the items is by ProductID.
When I add an item to the database, it is automatically assigned a ProductID.
However, I would like to be able to either
a) sort the list alphabetically by name, without changing the ProductID in the database or
b) add another column to the database called, for example: Rank, and have this list display the list by Rank, rather than by ProductID.
Here is my code. Any help in re-writing this section of the code to accomplish either a) or b) would be very helpful!
PS: I'm a little familiar with PHP and databases, but I am by no means an experienced coder.
$category = array_search(strtolower('upright'), $CFG["Category"]);
$product2 = new ProductData();
$where2 = sprintf(" WHERE CategoryID=%d ORDER BY ProductID DESC", $category);
$rows2 = $product2->GetRows($where2);
$count2 = count($rows2);
$line_count2 = 4;
$total_lines2 = ceil($count2/$line_count2);
// Photo
$photo5 = new PhotoData();
$thumb_array5 = array();
$count3 = count($rows2);
for ( $i = 0; $i < $count3; $i++ )
{
$ret = $photo5->Query($rows2[$i]["ProductID"]);
if ( $ret != 0 )
{
continue;
}
$thumb_array5[$photo5->Get("ProductID")] = $photo5->Get("Photo1");
}
Your SELECT query is not shown which I assume is coming from your ProductData() class. If you could change the source of your ProductData() that includes ranking, you could use a variable for ranking, like:
SELECT
#Ranking := #Ranking + 1 AS Rank,
productID,
product_name
FROM yourTable t, (SELECT #Ranking := 0) r
ORDER BY product_name;
Otherwise you could do it in your Php instead:
First change the ORRDER BY to your product name instead of product id:
$category = array_search(strtolower('upright'), $CFG["Category"]);
$product2 = new ProductData();
$where2 = sprintf(" WHERE CategoryID=%d ORDER BY Product_Name", $category);
Then in your php use a variable to do the ranking:
$count3 = count($rows2);
echo "<table><tr><th>Ranking</th><th>Product Name</th><th>Product Name</th></tr>";
for ( $rank = 0; $rank < $count3; $rank++ )
{
echo "<tr>";
echo "<td>$rank+1</td><td>".$rows2[$rank]["Product_name"]."</td><td><img src='".$photo5->Get("Photo1")."'></td>"
echo "</tr>";
}
echo "</table>";

how get and compare two mysql data?

table 1
two column >> paid - order_num1
table 2
two column >> order_num2
I want get order_num2 value from table 2 and
update paid(insert paid = 1) in table one with same order_num value
If order_num1=order_num2 then paid = 1 in table 1
$q = mysql_query("select order_num2 from table2 where samevalue = samevalue ");
$x = mysql_fetch_row($q);
mysql_query("update table1 set paid=1 where order_num1='$x['order_num2']'");
But it does not work!
First get from one table and update paid from another table if order_num have same value
Try
$table2 = mysqli_query("SELECT * FROM table2");
$row = mysqli_fetch_array($table2);
$num2 = $row['order_num2'];
$table1 = mysqli_query("SELECT * from table1");
$roww = mysqli_fetch_array($table1);
$num1 = $row['order_num1'];
if ($num2 == $num1) {
$updateDB = mysqli_query("UPDATE table1 SET paid = 1 WHERE order_num1 = '$num2'");
} else {
//Not equal so the paid column wont get updated
}

How to update a value by 1 if the new value inserted into the database clashes with value in the database?

I want to update the database of the sort order column to increase its value by one if the the new value inserted into the database clashes with the value that is already in the database. May I know how should I go about doing it? Please help! Thanks!
Below is my code (I am not sure whether am I on the right track):
$result = mysql_query("SELECT sortorder FROM information ORDER BY id ASC;");
if($result >= 1 ){
$i=1;
while ($initialorder = mysql_fetch_assoc($result))
{
$initialorder = $initialorder["sortorder"];
if ($sortorder == $initialorder ){
$result6 = mysql_query("SELECT * FROM information
WHERE `sortorder` = '$sortorder'");
$row6 = mysql_fetch_array($result6);
$removethis1 = $row6['id'];
$result7 = mysql_query("UPDATE information
SET `sortorder`= ((SELECT `sortorder`
FROM (SELECT MAX(`sortorder`) AS
'$initialorder' FROM information) AS '$initialorder') + 1)
WHERE id='$removethis1'");
}
$query = "INSERT INTO `information`
(`id`,`page`,`description`,`status`,`sortorder`,`keyword`,`date_added`)
VALUES
('$id','$title','$description','$status',
'$sortorder','$keyword','$date_added')";
$result = mysql_query($query, $conn);
header('Location: index.php?status=1&title='.$title);
$i++; }
}
You can do this:
INSERT INTO ON `information`
...
DUPLICATE KEY UPDATE
sortorder = '".$sortorder + 1." '

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