Updating a range of columns in mysql - php

I am having difficulty updating a range of columns using mysql. My overall goal is to give the user the ability to change a list item's position and to have all of the other list items shift position to accommodate for the change. So say you have a range of numbers, 1-6 and you would like to move the item in position 2 to position 4 and have each item compensate for the change while each occupying only a single position number. I have been working on this for a few hours now and I am getting too tired to think straight. I am still very much a newbie with mysql but I have almost finished making my first cms except for this last annoying tidbit.
The code in question is:
$newposition = $_POST['position'];
$oldposition = $_GET['oldposition'];
$id = $_GET['id'];
while ($work = mysql_fetch_array($workset)) {
if ($newposition>$oldposition) {
mysql_query('UPDATE work SET position=position-1 WHERE position<='.$newposition.' AND position>'.$oldposition.'');
mysql_query('UPDATE work SET position='.$newposition.' WHERE id='.$id.'');
}
elseif
($newposition<$oldposition) {
mysql_query('UPDATE work SET position=position+1 WHERE position<'.$oldposition.' AND position<='.$newposition.'');
mysql_query('UPDATE work SET position='.$newposition.' WHERE id='.$id.'');
}
elseif
($newposition==$oldposition) {
echo 'same value! ';
}
}
It creates the requested position change correctly but all of the other numbers in the range get changed to an incorrect value. It is probably a simple mistake..

See this line -
mysql_query('UPDATE work SET position=position+1 WHERE position<'.$oldposition.' AND position<='.$newposition.'');
Are you sure its correct ?
I think it should be
mysql_query('UPDATE work SET position=position+1 WHERE position > '.$oldposition.' AND position <= '.$newposition.'');

So, I came up with a solution for anyone that is interested. It isn't the cleanest, but it appears to have worked..
if ($newposition>$oldposition) {
for ($i=$oldposition+1; $i<=$newposition; $i++) {
$workset = mysql_query('SELECT * FROM work WHERE position='.$i.' LIMIT 1', $connection);
while ($work = mysql_fetch_array($workset)) {
mysql_query('UPDATE work SET position='.$i.'-1 WHERE position='.$i.'');
mysql_query('UPDATE work SET position='.$newposition.' WHERE id='.$id.'');
}
}
}
elseif
($newposition<$oldposition) {
for ($i=$oldposition-1; $i>=$newposition; $i--) {
$workset = mysql_query('SELECT * FROM work WHERE position='.$i.' LIMIT 1', $connection);
while ($work = mysql_fetch_array($workset)) {
mysql_query('UPDATE work SET position='.$i.'+1 WHERE position='.$i.'');
mysql_query('UPDATE work SET position='.$newposition.' WHERE id='.$id.'');
}
}
}
elseif
($newposition==$oldposition) {
}

Related

Stopping a PHP loop when updating MySQL database

I'm creating a basic main menu for a stock market simulator where the price of a company will be updated periodically. For testing purposes, I need to make a loop to display the price of a share on the website five times (with the website automatically updating without refreshing) and to update the database at the same time.
I have successfully wrote some code which will both update the database with the current share price and will also update the website as well. However, when I have tried to include a loop I have come to a problem. I have included a loop to iterate five times but the problem that I am having is that the code continues to iterate even after five tries.
PHP:
<?php
$conn = mysqli_connect("localhost", "root", "", "prices");
if ($conn->connect_error)
{
die("Connection error: ". $conn->connect_error);
}
$result = $conn->query("SELECT `price` FROM `priceTable` WHERE `company` = 'Bawden'");
$x = 0;
if ($result->num_rows > 0)
{
while ($row = $result->fetch_assoc())
{
echo $row['price'];
echo '<br><br>';
echo $x;
if ($x < 5)
{
$random = (rand(3300, 3700) / 100);
$sql = $conn->query("UPDATE `priceTABLE` SET `price` = '$random' WHERE `company` = 'Bawden'");
$x++;
}
}
}
?>
The above code will be displayed in a separate document with Javascript code and I can post this if required in the original post however I originally chose not to as I believe this is a PHP only problem. I have chosen to display $x to see if the value will increment. However, when running, the value of $x will stay at 0.
My expected result is that, on the website, there will only be five different updates and in the database, the database will only be updated five times.
However, my actual result is that the website and database are both continuously being updated, not stopping after five times.
I'm trying to limit the update command to only 5 updates yes. At the
moment, for testing purposes, there is only one company in my database
with one price only. So I'm updating this one company's price five
times
If you need to do the update 5 times for each row returned from the database, change your if statement to a for loop. Change this :-
if ($x < 5)
{
$random = (rand(3300, 3700) / 100);
$sql = $conn->query("UPDATE `priceTABLE` SET `price` = '$random' WHERE `company` = 'Bawden'");
$x++;
}
to this
for ($x = 0, $x < 5, $x++)
{
$random = (rand(3300, 3700) / 100);
$sql = $conn->query("UPDATE `priceTABLE` SET `price` = '$random' WHERE `company` = 'Bawden'");
}
This will repeat the process exactly 5 times and not rely on a separate counter (remove the other references to $x). Not sure why you would want to update the same record 5 times with different random values though.
The else will break the first loop, the second one will stop on the first while loop.
while ($row = $result->fetch_assoc())
{
echo $row['price'];
echo '<br><br>';
echo $x;
if ($x < 5)
{
$random = (rand(3300, 3700) / 100);
$sql = $conn->query("UPDATE `priceTABLE` SET `price` = '$random' WHERE `company` = 'Bawden'");
$x++;
}else{
break;
}
break;
}
What makes you think the loop should stop after 5 iterations?
You need to add the condition $x<5 in the while ($row = $result->fetch_assoc())
Edit following your comment
What you initially wrote is something like loop hundreds of times if need be and do something in the first 5 occurrences (starting loop 6, keep looping but do nothing).
Now for the 2nd half of your comment, I'm not sure what you mean.
What I see in your code is:
Select all prices for company = 'Bawden'
Update all the prices for company = 'Bawden' 5 times (loop) with a random value, the same one, on all the records.
Not enough information to tell for sure but I don't think it makes sense: on one hand, you except to have several records under company = 'Bawden (= reason why you created a loop), on the other hand, your update feels like it is written under the assumption there would be 1 record only...
Are you missing something like a price date from your table? What is the primary key of priceTable?
Try to post more technical details about your table (definition, sample of data) or it will be complicated to help further.

How to display one banner ad every third row in php?

Sorry for my English,
I need to display a banner ad from a database every third row in php. Banner ads and rows with the classified are selecting from database. To this moment I create something like this:
Rows with the classifieds from database:
while(#$row_select_kat = mysql_fetch_assoc($results_select_kat))
{
... //classifieds from database
if(($row_select_kat['id_ogloszenia']%3)==0)
{
$lim = 1;
echo"<div id=\"rek_poz_a\">";
modAddsDisplayHelper::wyswietlReklamyPozA();
echo"</div>";
}
}
Selecting banner ads from databes:
public static function wyswietlReklamyPozA()
{
$baza_danych = &JFactory::getDbo();
$query_sel_all_banners = "SELECT * FROM juxhv_banners";
$baza_danych->setQuery($query_sel_all_banners);
$baza_danych->query();
$banner_ads = $baza_danych->loadObjectList();
echo$query_sel_all_banners;
echo"Liczba x= ".$l_ogloszen;
foreach($banner_ads as $banner_ad)
{
if($banner_ad->state==1)
{
echo"$banner_ad->name<br/><img src=\"images/$banner_ad->username/bannerwerbung/$banner_ad->zdjecie\" width=\"434px\" height=\"94px\" />";
}
else
{
echo"No banner";
}
}
}
When I doing this in that way at every three rows displaying all three banner ads. How can I display only one banner ad every three rows?
URL: http://www.nachbarhilft.de
Greetings
You need to use external counter variable which will be incremented on each iteration and depending on its condition you can check modulo condition: Please see the following updated code.
[code]
$recordCount = 0;
while(#$row_select_kat = mysql_fetch_assoc($results_select_kat))
{
if(($recordCount%3)==0)
{
echo"<div id=\"rek_poz_a\">";
modAddsDisplayHelper::wyswietlReklamyPozA();
echo"</div>";
}
$recordCount++;
}
if($banner_ad->state == 1) {
echo"$banner_ad->name<br/><img src=\"images/$banner_ad->username/bannerwerbung/$banner_ad->zdjecie\" width=\"434px\" height=\"94px\" />";
break;
}
In this way you only print one banner, but always will be the first with state == 1 in the database.
Maybe is better improve the query:
$query_sel_all_banners = "SELECT * FROM juxhv_banners WHERE state = 1 LIMIT 1";
That will give you the same result, I think.
I hope it helps

Generate a Unique ID using PHP and MYSQL

Hi I am creating a system that processes and ID and a UID, The UID we are generating randomly but I am a little stuck, I need to always generate a UID that does not currently exist in the db as the field is a unique field used on the front end so as not to expose the real ID.
So to recap, I am trying to generate a unique id that does not currently exist in the DB the part I haven't got working is the cross checking in the db so it sometimes will give a number that already exists in the db even though it shouldn't thanks in advance.
This is my code so far:
function uniqueID($table)
{
$db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$possible = '1234567890';
$code = '';
$characters = mt_rand(7,14);
$i = 0;
while($i < $characters)
{
$code .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
$i++;
}
$result = $db->query('
SELECT uniqueID
FROM '.$table.'
WHERE uniqueID = "'.$code.'"
LIMIT 1
');
$totalRows = $result->num_rows;
if(!$result)
{
return $db->error;
}
else
{
if($totalRows > 0)
{
return uniqueID($table);
}
else
{
return $code;
}
}
}
http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_uuid
To generate unic UID you can use time, i think it was a very small chanse that records will be added in the same second, with two random data.
write some function which return it to you like that
function generate_uid(){
return md5(mktime()."-".rand()."-".rand());
}
In PHP there's a function called uniqid()
http://php.net/manual/en/function.uniqid.php
I could talk about generating ids, like the others did, but this is not your question.
Your query seems fine. If it returns 0 rows but you seem to find the code in the database, then most likely it only looks the same, but actually isn't. It could be padded by whitespace.
One way to solve this is by selecting the last row of your user database and have your script to check for the id field (you can achieve this by performing a select ordering by ID in descendent mode) then you can use that info for randomize numbers greater than that ID.
EDIT
$result = $db->query('
SELECT uniqueID
FROM '.$table.'
');
$already_in_database = array();
while ($row = mysql_fetch_array($result)){
$already_in_database[] = $row['UID'];
}
$new = rand(0,$some_max_value);
while(in_array($new,$already_in_database)){
$new = rand(0,$some_max_value);
}
I figured out what the problem was already, As I mentioned to everyone the code generation was not the issue! The issue was that the cross check was not working correctly. So all I did was removed this loop
while($i < $characters)
{
$code .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
$i++;
}
As this was causing my unique ID to end up wrong.

goto equivalent for php version < 5.3.0?

I need to use the goto operator in my code as I can't seem to think of a way around it. However the problem is my host only has PHP version 5.2.17 installed.
Any ideas?
Below is my code:
if ($ready !=="y")
{
$check=mysql_query("SELECT `inserted` FROM `team`");
$numrows = mysql_num_rows($check);
$i="0";
while ($i<$numrows && $row = mysql_fetch_assoc($check))
{
$array[$i] = $row['inserted'];
$i++;
}
if (in_array("n", $array))
{
goto skip;
}
else
{
mysql_query("
UPDATE game SET ready='y'
");
}
}
skip:
There are a few anti-patterns in your code. Let's clean it up. I'll explain what's been changed in a jiffy.
if($ready !== "y") {
$sth = mysql_query("SELECT inserted FROM team WHERE inserted = 'n'");
if(mysql_num_rows($sth) > 0) {
mysql_query("UPDATE game SET ready = 'y'");
}
}
First things first: There is no need to perform a query, fetch all of the results, then loop through those results (in_array) looking for a specific value. Let the database do that for you by expressly looking only for rows where inserted is the string literal "n".
Because we know that we're only getting "n" records back, we just need to check if there are any results. If so, run the query. If there are no "n" records, the UPDATE isn't run.
If you need to know that the UPDATE ran, add a check for it:
$ran_update = false;
if($ready !== "y") {
$sth = mysql_query("SELECT inserted FROM team WHERE inserted = 'n'");
if(mysql_num_rows($sth) > 0) {
mysql_query("UPDATE game SET ready = 'y'");
$ran_update = true;
}
}
if($ran_update) {
// ...
}
You want to use the correct control word to break from the loop:
if ($ready !=="y")
{
$check=mysql_query("SELECT `inserted` FROM `team`");
$numrows = mysql_num_rows($check);
$i="0";
while ($i<$numrows && $row = mysql_fetch_assoc($check))
{
$array[$i] = $row['inserted'];
$i++;
}
if (in_array("n", $array))
{
break;
}
else
{
mysql_query("
UPDATE game SET ready='y'
");
}
}
The break keyword will do exactly what you want: End the execution of the while loop. Never ever ever use a goto!
As a direct response to the title of this post:
do{
if (!$condition){
break;
}
// Code called if conditions above are met
}while(0);
//Code always called
In some circumstances, this, or a goto, can make for very tidy and readable code.
First, you could use a break to exit your initial loop. Second, if you need to test for anything, set a variable (must be global not local) as a flag or indicator before calling break, then do a conditional test statement where your skip line is to perform any additional steps you need.

PHP Function Dependent on presence of MySQL data entry

I code a weekly trivia program for one of my clients through facebook.
I have a bit of code commented out where we display the winner when we need to. Currently I just remove the comment brackets and update when it's time to display. I'm trying to make this so someone non-savvy can handle updates so I've moved my code into an include:
winner-display.php
I am trying to write a function so that if the winner is set in MySQL, it includes the file in-line, and if the winner field is empty in the database, it does not.
Here is what I have so far, any ideas?
<?php
$target="3";
$myDataID = mysql_query("SELECT topic_desc from ref_links WHERE ref_categories_id = '$target' AND topic_name = '$property'", $connectID);
while ($row = mysql_fetch_row($myDataID)) {
$displayvalue = $row ['topic_desc'];
}
if ( $displayvalue != 'null') {
include('../includes/winner-display.php');
} else {
}
?>
Ok, thanks for helping guys, got it to work as:
<?php
$target="3";
$myDataID = mysql_query("SELECT topic_desc from ref_links WHERE ref_categories_id = '$target' AND topic_name = '$property'", $connectID);
while ($row = mysql_fetch_row($myDataID)) {
foreach ($row as $field) {
if ($field != null) {
include('../includes/winner-display.php');
}
}
}
?>
You can definitely put an include within an if. That solution that you posted should work as you would like it to, although I personally would have used a function instead of a completely separate file to include (although that is personal preference).
All you have to do to make it work is remove the quotes around 'null'.
<?php
$target="3";
$myDataID = mysql_query("SELECT topic_desc from ref_links WHERE ref_categories_id = $target' AND topic_name = '$property'", $connectID);
while ($row = mysql_fetch_row($myDataID)) {
$displayvalue = $row ['topic_desc'];
}
if ( $displayvalue != null) {
include('../includes/winner-display.php');
}
?>
Keep in mind that if your query returns more than one row, only the last row will be retained. I don't know if that is the functionality you want (in which case, there are some changes you could make, just ask me to edit my answer), but I didn't change that.

Categories