| id | url | title | menu_id |
------+--------+--------+----------
| 1 | http://| link 1 | 1 |
| 2 | http://| link 2 | 2 |
| 3 | http://| link 3 | 3 |
| 4 | http://| link 4 | 4 |
Hi, I was wondering if its possible using PHP to reorder the above to something like below. I am trying to generate a menu which can easily be reordered by clicking an up or down arrow. I have no idea where to start. Any help would be much appreciated.
| id | url | title | menu_id |
------+--------+--------+----------
| 1 | http://| link 1 | 2 |
| 2 | http://| link 2 | 4 |
| 3 | http://| link 3 | 3 |
| 4 | http://| link 4 | 1 |
I went with using the following code
$menu_id = $_GET['page_id'];
$page_order = $_GET['page_order'];
if ($_GET['do'] == 'up') {
mysql_query("UPDATE menu SET menu_order = '$page_order' +1 WHERE id != '$menu_id' AND menu_order < '$page_order'");
mysql_query("UPDATE menu SET menu_order = menu_order -1 WHERE id = '$menu_id'");
} else if ($_GET['do'] == 'down') {
mysql_query("UPDATE menu SET menu_order = '$page_order' -1 WHERE id != '$menu_id'");
mysql_query("UPDATE menu SET menu_order = menu_order +1 WHERE id = '$menu_id'");
}
It's definitely possible, but you have to do a little bit of extra logic, it's not something that can be done in one query.
Think about the steps when you click an up/down arrow. For example, let's say that you start with the items in the order 1, 2, 3, 4 and then you click the up arrow on #3. Two things have to happen to change the order to 1, 3, 2, 4:
3's position changes to 2 (it gets decreased by 1)
2's position changes to 3 (it gets increased by 1)
So you have to change the position for the item that they clicked up on, as well as the one that was previously in its new position. Clicking a down arrow is almost the same, but with the increase/decrease reversed.
I had the same problem, and solved it with an if statement query. Here is step by step instructions:
1.
get the position of the item before updating mysql.
$query = "SELECT * FROM table WHERE id=1;
$result = mysql_query($query);
$item = mysql_fetch_array($result);
$old_position = $item["position"];
we had a form in the page so we get the new position from $_POST data.
$new_position = $_POST["position"];
we determine if we moved the item up or down
if ($new_position > $old_position) { //moved it down
$query = "UPDATE table SET position = position-1 WHERE position >= {$old_pozisyon} AND position <= {$new_pozisyon} and id <> {$id}";
}
and we do the same for the other condition but we make position+1 this time. Hope this helps
#DaveE has the right idea but results in all sorting data being either one higher or lower (depending on direction) for the other rows. Here's my PHP/MySQL:
if ($direction == 'up') {
$q1 = "UPDATE table SET sort = ($sort +1) WHERE id != $pgid AND sort = ($sort -1);";
if($r = mysqli_query($q1, $dbsvr)) {
$q2 = "UPDATE table SET sort = (sort -1) WHERE id = $pgid;";
$r = mysqli_query($q2, $dbsvr);
}
} else if ($direction == 'down') {
$q3 = "UPDATE table SET sort = ($sort -1) WHERE id != $pgid AND sort = ($sort +1);";
if($r = mysqli_query($q3, $dbsvr)) {
$q4 = "UPDATE table SET sort = (sort +1) WHERE id = $pgid;";
$r = mysqli_query($q4, $dbsvr);
}
} else {
echo 'no direction';
}
Related
I mean, I have a referral system which is every parent_id has parent and the parent_id of that parent until it gets to the last parent which is the Senior.
Given that a user has purchased an item and it is successful, now I am calling the insertEarnings function to insert the corresponding amount to his parent_id, if his parent_id is Junior his parent_id will get 100.
This is how the question begin, what if his parent doesn't have a rank meaning not active, the amount to be insert to his parent_id will go through the next rank which is the Premium so the Premium will no have 250 total, after that proceed the normal insertion of the amount to the parent_id of Premium which is the Advanced- he will get the corresponding amount which is 200, because the rank below him which is the Premium is existing, the insertion will go through until it gets to the last rank which is the Senior
Imagine that it is looping through the parent until it gets to the last rank - Senior.
The ranks are in order
Junior
Premium
Advanced
Senior
Ranks with their corresponding amount value
Junior - 100
Premium - 150
Advanced - 200
Senior - 250
Users table
+------+------------+-------------+------------+
| id | username | parent_id | rank |
+------+------------+-------------+------------+
| 1 | john | NULL | Senior |
| 2 | jane | 1 | Advanced |
| 3 | josh | 2 | Premium |
| 4 | joey | 3 | Junior |
| 5 | jade | 4 | Basic |
+----------------------------------------------+
Code
$user_id = 5; // jade
$parent_id = 4;
// call the function to insert the earnings
self::insertEarnings($user_id,$parent_id);
private function insertEarnings($user_id,$parent_id) {
if ($parent_id > 0) {
$user_parent = $parent_id;
$has_parent = true;
// start iteration
while($has_parent == true){
$account = User::where('id',$user_parent)->first();
$amount = 0;
if ($account->rank == "Junior" ) {
$amount = 100;
} elseif ($account->rank == "Premium") {
$amount = 150;
// for example this user/parent does not exist the amount(150) for him will be added to the next rank which is the Advance
} elseif ($account->rank == "Advanced") {
$amount = 200;
} elseif ($account->rank == "Senior") {
$amount = 250;
// set to false to stop the iteration
$has_parent = false;
}
$earnings = new Earnings;
$earnings->user_id = $account->id;
$earnings->amount = $amount;
$earnings->save();
$next_parent = User::where('id',$user_parent)->first();
$user_parent = $next_parent->parent_id;
if($user_parent == 0){
$has_parent = false;
}
}
}
}
The $user_id is not used in this example, but there's a use to that that didn't included in the question because that is not the main problem.
i've got a database with the folowing info:
--------------
id | Book | Names
1 | 1 | Tom
2 | 8 | James
3 | 10 | Tom
4 | 2 | Tom
5 | 17 | James
6 | 2 | James
7 | 9 | James
8 | 7 | Tom
9 | 8 | Tom
This table shows books read by "Tom" and "James".
These are the requirements i need:
to show the next book not read. (eg. Tom's would be '3' and James's '1')
to skip book '1', '10' and '15' as these are no longer available. (so in James's case, the next book would be '3')
if it cannot be sequential, any random book not read will do as well.
here's what i did:
$sql = "Select * FROM books Group By names";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$sql1 = "SELECT * FROM books WHERE names = '" . $row["names"]. "' ORDER BY book ASC";
$result1 = $conn->query($sql1);
if ($result1->num_rows > 0) {
$newbook = '1';
// output data of each row
while($row1 = $result1->fetch_assoc()) {
if ($row1["book"] == $newbook) {
echo "Exist<br><br>";
$newbook = $newbook+ 1;
} else {
if ($row1["book"] == '1' || $row1["book"] == '10' || $row1["book"] == '17') {
$newbook= $newbook+ 1;
} else {
echo "Add".$newbook."<br><br>";
break;
}
}
}
}
}
}
This is how far i've got. All help appreciated. Thanks
Off the top of my head, a calendar table approach might be a good solution to handle this problem completely in MySQL. First define a sequence table, containing the values from 1 to the highest book ID (I call this table seq_table). Then, to find the lowest book not read by a given user, a simple left join will do the trick:
SELECT MIN(t1.Book) AS next_book
FROM seq_table t1
LEFT JOIN books t2
ON t1.Book = t2.Book AND
t2.Names = 'Tom'
WHERE
t2.Book IS NULL;
If you instead wanted to choose a random book not read by Tom, then we can use the following query:
SELECT t1.Book AS next_book
FROM seq_table t1
LEFT JOIN books t2
ON t1.Book = t2.Book AND
t2.Names = 'Tom'
WHERE
t2.Book IS NULL
ORDER BY RAND()
LIMIT 1;
you will need another table to store available books let say books table
---------------------------------------------
id | Book_Title | Available
---------------------------------------------
1 | One million promises | no
2 | Two towers | yes
3 | Three musketeers | yes
4 | 4th Avenue Cafe | yes
5 | Famous Five | yes
6 | Six million dollar man | yes
7 | Seven Stars | yes
8 | Eighth Paladin | yes
9 | Ninth Heaven | yes
lets say that your read books table is named read_books, you can get the next book to read by Tom with this query:
select min(id) from books where Available='yes' and id not in (select book from read_books where names = 'Tom')
I have two tables in my MySQL database:
1 named "stock"
id | product | qty
----------------------
1 | 1 | 15
----------------------
2 | 1 | 20
And the second one named "orders"
id | product | qty | stock_id
----------------------------
1 | 1 | 7 | 1
-----------------------------
2 | 1 | 8 | 1
So, before register a new "order", I need to verify which "stock.id" has free product to sell, with SUM all existent orders.qty and subtract it to stock.qty, for this example I'm going to insert a new order of 10 pieces of product with id '1' ($new_order = '10' (pieces):
for each stock.id { SUM(orders.qty) as total | then verify if 'total' >= $new_order | if(total >= $new_order){select that stock.id} if don't { continue looking for an stock.id with free product for sale } }
Hoping to make myself known, I need your help to structure MySql query from PHP for that function.
UPDATE
I've solved with this double query:
<?
$queryL = "SELECT id,unidades,producto FROM stock WHERE `producto` = '$producto'";
$resultL = $mysqli->query($queryL);
/* array asociativo */
while($rowL = mysqli_fetch_array($resultL, MYSQLI_ASSOC))
{
$id_lote = $rowL['id'];
$unidades = $rowL['unidades'];
$queryD = "SELECT SUM(cantidad) as total FROM `pedidos` WHERE `lote` = $id_lote";
$resultD = $mysqli->query($queryD);
/* array asociativo */
if($rowD = mysqli_fetch_array($resultD, MYSQLI_ASSOC)){
$ventas = $rowD['total'];
$disponible = $unidades - $ventas;
if($disponible >= $cantidad){ $lote = $id_lote; }
}
}
?>
Can someone help me simplifying this?
i am try to update a mysql table with a PHP instance query.
but I do not know how to put the query correctly or whether there is a logical part it works specified side mysql or if i can do with php.
i get the data from a web form with 2 field the ID(It is the autoincrementable ID in MySQL) and a input with the new order.
Update Case 1: Change Order Update Data
ID=3
Imput=5
Original table 1
+--------+---------+
| ID | Order |
+--------+---------+
| 1 | 1 |
| 3 | 3 |
| 4 | 4 |
| 5 | 5 |
| 6 | 6 |
| 7 | 10 |this have a Hole from last registre order need preserve
| 8 | 11 |
+--------+---------+
Table
+--------+---------+
| ID | Order |
+--------+---------+
| 1 | 1 |
| 2 | 2 |
| 3 | 5 |Updated
| 4 | 6 |Updated
| 5 | 7 |Updated
| 6 | 8 |Updated
| 7 | 12 |Update, preserve and continue the hole
| 8 | 13 |Update, and Continue if more record
+--------+---------+
Update Case 2: Inserting a new record and modify the order.
ID=2
Imput=4
Original table 2
+--------+---------+
| ID | Order |
+--------+---------+
| 1 | 1 |
| 7 | 10 |this have a Hole from last registre order need preserve
| 8 | 11 |
+--------+---------+
Table
+--------+---------+
| ID | Order |
+--------+---------+
| 1 | 1 |
| 2 | 4 |record Inserted
| 7 | 10 |preserve no need update
| 8 | 11 |
+--------+---------+
I need some cycles, but do not know what conditions apply.
basics sorry for my example but I am not very expert
Update 1 Legancy
<?php
#Get Values from input Dinamical:
# $i_txt_1 = ID
# $i_txt_3 = New Order
# Attention: this is not the correct syntax for PHP, they are guidelines on what to do at every step, and that must be taken into account for the creation of the string of update.
foreach ($_POST as $key => $value){
${$key} = trim(addslashes(strip_tags($value)));
}
#collector output message
$psmg = '';
#statement prepared for the query updater
$stmtpreUP ="";
#save this variable the current date using some specific function.
$DateUD;
#We keep the variable that is the form that represents the ID
$ID = $i_txt_1;
#first condition
1. search the database if the ID exists we receive the form.
result 0{
throw new Exception You can not modify a nonexistent parameter. Search before Change
}
#second condition
2. if order is the same that the current order display MSG
{
$psmg.='<br>Update was not carried out in the Order';
}
#third condition
3. if check if it exists, any record or ID, with the order comes from the form.
result 0{
update: Create a direct update using the new order and id.
}else{
#Important Step : detecting whether an increase or decrease in the order
4. $GViD = $i_txt_3 - order;
if ($GViD < 0){
#in case is decreasing the order
$stmtpreUP .="UPDATE Table SET Order= $i_txt_3, DateUD= DateUD WHERE ID = $i_txt_1"; #String update for the ID target
#Generate the string updater for the following rows, contemplating that, if a decrease in these rows ID target should be avoided.
5.
GET "SELECT ID, Order FROM Table WHERE Order >= ".$i_txt_3." ORDER BY Order ASC";
$count = $i_txt_3; #need a counter
#Cicle to generate Update String
6.
while ($datos = mysqli_fetch_array($Get)){
#condition to ignore the target ID and update only up to the target ID range, avoid overuse of resources
if($datos['ID']!==$ID AND $datos['ID']<$ID ){
$idUD = $datos['ID'];
$count = ++$count;
$neworder = $count;
#concatenation to the Update String
$stmtpreUP .= "UPDATE table SET Order = ".$neworder.", DateUD ='".$DateUD."' WHERE ID ='{$idUD}';";
}
}
}else{
#in case is Increase the order
$stmtpreUP .="UPDATE Table SET Order= $i_txt_3, DateUD= DateUD WHERE ID = $i_txt_1"; #String update for the ID target
#Generate the string updater for the following rows, contemplating that, if a decrease in these rows ID target should be avoided.
7.
GET "SELECT ID, Order FROM Table WHERE Order >= ".$i_txt_3." ORDER BY Order ASC";
$count = $i_txt_3; #need a counter
#Cicle to generate Update String
8.
while ($datos = mysqli_fetch_array($Get)){
#condition to ignore the target ID and update all the next Order for all the table to preserver spaces into order
if($datos['ID']!==$ID){
$idUD = $datos['ID'];
$count = ++$count;
$neworder = $count;
#concatenation to the Update String
$stmtpreUP .= "UPDATE table SET Order = ".$neworder.", DateUD ='".$DateUD."' WHERE ID ='{$idUD}';";
}
}
}
}
#Run the update of all the statement
9. #function to run mutiple statement updates.
BDupdateM($stmtpreUP);
$psmg.='Datos Actualizado Correctamente';
10. output all MSG
echo $psmg;
?>
Why would you want to make something like that man, you are approaching it the wrong way IMO such a thing will be so expensive (performance wise).
If you want to ORDER BY ID, then by Order you just need to make a SELECT statement like
SELECT * FROM table ORDER BY id,order
<?php
#Get Values from input Dinamical:
# $i_txt_1 = ID
# $i_txt_3 = New Order
# Attention: this is not the correct syntax for PHP, they are guidelines on what to do at every step, and that must be taken into account for the creation of the string of update.
foreach ($_POST as $key => $value){
${$key} = trim(addslashes(strip_tags($value)));
}
#collector output message
$psmg = '';
#statement prepared for the query updater
$stmtpreUP ="";
#save this variable the current date using some specific function.
$DateUD;
#We keep the variable that is the form that represents the ID
$ID = $i_txt_1;
#first condition
1. search the database if the ID exists we receive the form.
result 0{
throw new Exception You can not modify a nonexistent parameter. Search before Change
}
#second condition
2. if order is the same that the current order display MSG
{
$psmg.='<br>Update was not carried out in the Order';
}
#third condition
3. if check if it exists, any record or ID, with the order comes from the form.
result 0{
update: Create a direct update using the new order and id.
}else{
#Important Step : detecting whether an increase or decrease in the order
4. $GViD = $i_txt_3 - order;
if ($GViD < 0){
#in case is decreasing the order
$stmtpreUP .="UPDATE Table SET Order= $i_txt_3, DateUD= DateUD WHERE ID = $i_txt_1"; #String update for the ID target
#Generate the string updater for the following rows, contemplating that, if a decrease in these rows ID target should be avoided.
5.
GET "SELECT ID, Order FROM Table WHERE Order >= ".$i_txt_3." ORDER BY Order ASC";
$count = $i_txt_3; #need a counter
#Cicle to generate Update String
6.
while ($datos = mysqli_fetch_array($Get)){
#condition to ignore the target ID and update only up to the target ID range, avoid overuse of resources
if($datos['ID']!==$ID AND $datos['ID']<$ID ){
$idUD = $datos['ID'];
$count = ++$count;
$neworder = $count;
#concatenation to the Update String
$stmtpreUP .= "UPDATE table SET Order = ".$neworder.", DateUD ='".$DateUD."' WHERE ID ='{$idUD}';";
}
}
}else{
#in case is Increase the order
$stmtpreUP .="UPDATE Table SET Order= $i_txt_3, DateUD= DateUD WHERE ID = $i_txt_1"; #String update for the ID target
#Generate the string updater for the following rows, contemplating that, if a decrease in these rows ID target should be avoided.
7.
GET "SELECT ID, Order FROM Table WHERE Order >= ".$i_txt_3." ORDER BY Order ASC";
$count = $i_txt_3; #need a counter
#Cicle to generate Update String
8.
while ($datos = mysqli_fetch_array($Get)){
#condition to ignore the target ID and update all the next Order for all the table to preserver spaces into order
if($datos['ID']!==$ID){
$idUD = $datos['ID'];
$count = ++$count;
$neworder = $count;
#concatenation to the Update String
$stmtpreUP .= "UPDATE table SET Order = ".$neworder.", DateUD ='".$DateUD."' WHERE ID ='{$idUD}';";
}
}
}
}
#Run the update of all the statement
9. #function to run mutiple statement updates.
BDupdateM($stmtpreUP);
$psmg.='Datos Actualizado Correctamente';
10. output all MSG
echo $psmg;
?>
I am using MySQL and cPANEL for making my website. I'm having a problem in figuring out how to make manual likes function (Facebook like button, or YouTube thumbs up button).
Am I going in the right way to make a "like" button in my website?
VIDEOTABLE:
+----+----------+-----------+
| ID | VIDEO URL| LIKES |
+----+----------+-----------+
| 1 | example 1| 5774 |
| 2 | example 2| 9654 |
| 3 | example 3| 1254 |
| 4 | example 4| 7656 |
| 5 | example 5| 6757 |
| 6 | example 6| 5675 |
| 7 | example 7| 4565 |
+----+----------+-----------+
ID is my serial
VIDEO_URL is my page link or the video link
likes is the users liking this
So, to like the video when USER will clicks the like button without login it will redirect and show the login panel. Then, user will login into it via FACEBOOK or TWITTER so the site can get the USER_ID
Ones the user logins there likes option their will be this code (NOT SURE)
SQL> UPDATE VIDEOTABLE
SET ID = '3', LIKES = ????;
How can i increase +1 value in the table? And then when the USER likes it, the site refreshes and shows the latest value (by increasing by +1).
My Second Problem = How can i restrict the user by giving only one chance to increase the like) and to undo Rollback Query.
You should be able to use the following:
UPDATE VIDEOTABLE SET LIKES=LIKES+1 WHERE ID=3;
However, it may be wise to set a separate lookup table that indicates whether a particular user has already 'liked' something, so that they may not 'like' it more than once.
That table would look like this:
tblLikesLookup
+----+--------+--------+
| ID | videoID| userID |
+----+--------+--------+
| 1 | 1 | 10 |
| 2 | 3 | 7 |
| 3 | 2 | 10 |
| 4 | 8 | 8 |
| 5 | 6 | 8 |
+----+--------+--------+
You could even use this table in place of your VIDEOTABLE to store your likes. To get the number of likes for any given video,
SELECT COUNT(*) FROM tblLikesLookup WHERE videoID=[videoID];
or for all videos,
SELECT COUNT(*) FROM tblLikesLookup GROUP BY videoID;
This may eventually become slow as the volume to your site increases, in which case using a separate counter like the one you have above will come in handy.
if i understand you right,
you can simple increase any number like that:
update VIDEOTABLE set LIKES = LIKES + 1 where ID = ...
so as the same to reduce likes
update VIDEOTABLE set LIKES = LIKES - 1 where ID = ...
it is not important what the user id is. You need video ID
EDIT:
if you want to prevent multiple likes, you need a new table too.
TABLE: USER_TO_LIKES
id | user_id | video_id
so you must firstly check if user liked it before:
$c = mysql_num_rows(mysql_query("select id from USER_TO_LIKES where video_id = 11 and user_id = XX"));
if($c == 0){
mysql_query("update VIDEOTABLE set LIKES = LIKES + 1 where ID = 11 ");
mysql_query("insert into USER_TO_LIKES set video_id = 11, user_id = XX");
}
If unlike:
$c = mysql_num_rows(mysql_query("select id from USER_TO_LIKES where video_id = 11 and user_id = xx"));
if($c > 0)
{
mysql_query("update VIDEOTABLE set LIKES = LIKES - 1 where ID = 11");
mysql_query("delete from USER_TO_LIKES where video_id = 11 and user_id = XX");
}
thats it.
EDIT2: see above
You Will Need the video id And The User That has clicked And Another Table(Called Liked_People) For People Who Has Already Liked Something like that:
+-------+---------+
|UserId |VideoId |
+-------+---------+
|1 |5739 |
+-------+---------+
Now Wen The User Click On Like Send An XMLHTTP request to that PHP function:
function Like($usrid , $vidid){
//usrid = userid And vidid = video id
$Comm1 = $Con->prepare("SELECT * FROM Liked_People WHERE UserId = ? And VideoId = ?");
$Comm1->execute(Array($usrid , $vidid);
if($Comm1->rowCount() == 0){
$Comm2 = $Con->prepare("INSERT INTO Liked_People (UserId , VideoId) VALUES (?,?)");
$Comm2->execute(Array($usrid , $vidid));
$Comm3 = $Con->prepare("SELECT Likes FROM VideoTable WHERE Id = ?");
$result = $Comm3->Execute(Array($vidid));
$final = $result + 1;
$Comm4 = $Con->prepare("UPDATE VideoTable SET Likes=? WHERE ID = ?");
$Comm4->Execute(Array($final , $vidid));
}else { return false;}
}
And That is but if you want to get A list of the usernames that has liked lets say that you have the People Table Like That:
+-------+--------------+
|Id |Username |
+-------+--------------+
|1 |Ahmad Mehmet |
+-------+--------------+
And This is the Code:
function get_likers($vidid){
if($vidid == null or $vidid == "" or $vidid == 0){
return false;
}
$Comm1 = $Con->prepare(SELECT UserId FROM Liked_People WHERE VideoId = ?);
$Comm1->Execute(Array($vidid));
$arr = $Comm1->fetchAll();
$finale = Array();
$i = 0;
foreach($arr as $row){
$Comm = $Con->Prepare("SElECT Username WHERE Id = ?");
$finale[$i] = $Conm->Execute(Array($row[0]));
$i++;
}
return $finale
}
This function is just for backups and Not essential.
function Work_Array($Arr){
echo '<table border="2">';
echo '<tr><th>Users That Has Liked</th></tr>';
foreach($Arr as $el){
echo"<tr><td>";
echo $el;
echo "</td></tr>";
}
echo "</table>";
}
Called Like That:
work_array(get_likers($vidid));
Questions?:D