Checking to see if a MySQL row is populated - php

I have a page that writes to a MySQL table. The table has a set amount of rows (24).
I have an $id variable that's set by a rand() function. I basically want to pull the row at that $id, so if $id was 3, I want to pull the third row. Then, I want to check if there is a price set at that row (indicating that the row is being used). If there is no price, I want to keep $id at the value it has been set at and proceed with the query. If there is a price, I want to re-randomize the $id variable, and check again if that row is used up. When it finds an empty row, proceed with the query.
My solution semi-works, but it seems to have a <10% chance of overwriting a used row, for some reason. I want it to never overwrite a used row.
Here's my code:
mysql_select_db("delives0_booklet", $con);
$query = "SELECT * FROM booklet WHERE id = '$id'";
$res = mysql_query($query,$con);
$newId = $id;
while($row = mysql_fetch_array($res))
{
if($row['price'] != 0)
{
do{
$newId = rand(1, 24);
}while($newId == $id);
}
}
$id = $newId;
mysql_query("UPDATE booklet SET price = '$price', advertiser = '$advertiser', image = '$image', monthsRemaining = '$monthsRemaining', availability = 1 WHERE id = '$id'");
Edit
I had the idea to do this. I loop through the table and I put the 'id' of each unfilled spot into an array. Then I pick randomly from that array. However, there seems to be a bug that I can't find, since the array keeps showing as having nothing in it, even after the loop is run, and $i is the correct figure.
mysql_select_db("delives0_booklet", $con);
$query = "SELECT * FROM booklet";
$res = mysql_query($query,$con);
$i = 0;
$isEmpty = array();
while($row = mysql_fetch_array($res))
{
if($row['price'] == 0)
{
$isEmpty[i] = $row['id'];
$i = $i + 1;
}
}
echo $i . " unfilled spots.";
$n = 0;
while($n<$i)
{
echo $isEmpty[$n];
$n = $n + 1;
}
if($i > 0)
{
$id = $isEmpty[rand(0, $i)];
}
if($i == 0)
{
echo 'All spots have been filled.';
}

I think it is a top level logic problem. Because you populate with random ids, you can get duplicate ids, and so when you update "WHERE id = '$id'" you may be picking up rows already populated.
I don't know your goal, but perhaps using an auto-increment id, and dropping rows that you want to get rid of, is the way to go. A rolling set of rows (24 at a time) but with ever increasing ids, would prevent mistaking one for the other.

If I understand the problem correct, this should work:
SELECT *
FROM booklet
WHERE price = 0 OR price IS NULL
ORDER BY RAND()

Related

Trying to randomize where a name is inserted into a table using PHP and SQL

What I'm trying to accomplish is randomize elements of an array which contain column names. Then use those randomized columns names to insert a name into a table.
Here is the code I have and its causing a Internal Server Error.
$sql3 = "SELECT * FROM players";
$result3 = $con->query($sql3);
while ($row3 = $result3->fetch_assoc()) {
$num_bracket1 = $row3["num_bracket"];
$name = $row3["name"];
$y = 1;
while ($y <= $num_bracket1) {
shuffle($bracket_array);
shuffle($player_array);
$sql4 = "UPDATE brackets SET ".$player_array[0]."='".$name."' WHERE bracket_num='".$bracket_array[0]"'";
$result4 = $con->query($sql4);
}
}
It's an obvious infinite loop, you forgot to increment $y inside the while and it never ends.

Get sum of each row added together in while loop

So I have a mysql table that contains an integer in each row. What I am trying to do is get the sum of the integers. Here is what I currently have that is working.
$cn = 0;
$sql = mysqli_query($con,"SELECT * FROM members WHERE member='$userid'");
while($row = mysqli_fetch_array($sql)) {
$i = $row['number'];
$cn = $cn + $i;
}
echo $cn;
So I make $cn equal zero then each time it goes through the loop it will add the number from the matching row.
Does anyone have a better idea on how to accomplish this? Thanks!
You don't need to use PHP or here a loop for that, because your database can do the job for you.
$sql = mysqli_query($con,"SELECT sum(number) FROM members WHERE member='$userid'");
If you want the sum of the column number for each member with a particular user id
$sum = 0;
$sql = mysqli_query($con,"SELECT SUM(number) as number_total FROM members WHERE member='$userid'");
while($row = mysqli_fetch_array($sql)) {
$sum = $row['number_total'];
}
$sum will have the total

Not able to extract all values of a column in mysql

I am having problem extracting values from a mysql table:
I need to get all values of picname column from a table where uid condition is satisfied.
Now i have two rows where this condition is satisfied but i am getting output only for 1st case. I am not able to get the second row's value. 1st rows value repeats again for second time.
$i = 0;
for($i;$i<2;$i++)
{
$s = "SELECT picname FROM uploaded_data WHERE uid='$uid'";
$que = mysql_query($s,$db);
while($num = mysql_fetch_array($que))
{
echo $name ['picname'];
}
}
Thank You
it should not give you any result you do not have
$name
should be:
$i = 0;
for($i;$i<2;$i++)
{
$s = "SELECT picname FROM uploaded_data WHERE uid='$uid'";
$que = mysql_query($s,$db);
while($num = mysql_fetch_array($que))
{
echo $num['picname'];
}
mysql_free_result($que);
}

Is there a more efficient way to do this

function countBrand($brand_id, $brand_name) {
$sql = "SELECT brand FROM coupons WHERE expire >= CURRENT_DATE AND brand='".$brand_id."'";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
echo '<li>'.$brand_name.'</li>';
}
function brandCount() {
$sql = "SELECT DISTINCT brand,brand_id,brand_name FROM coupons,coupons_brand WHERE brand=brand_id AND expire >= CURRENT_DATE ORDER BY brand_name";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$num = mysql_num_rows($result);
echo '<h3>'.$num.' Brands</h3>';
echo '<ul>';
$i = 0;
while ($i < $num) {
$brand_id = mysql_result($result, $i, "brand_id");
$brand_name = mysql_result($result, $i, "brand_name");
countBrand($brand_id, $brand_name);
$i++;
}
echo '</ul>';
}
It works perfectly and gives me the results I am looking for. I am not as strong with sql statements as I would like to be. Is there a way I could do this that would be more efficient, it seems very slow.
Basically, it counts how many brands have coupons, then coupons how many coupons each brand has..
I also, on the same page, do this for categories. There are a few thousand categories and maybe 20,000 coupons.
there are a few php optimisations you could do, but they probably wont save you much time, compared to adding an index to mysql on the correct columns
i have commented some php optimisations below, maybe of interest to you anyway
given the simple nature of the functions, it is not necessary to have 2 functions, and that would save the timecost of calling countBrand(), (although it is a pretty minimal time saving)
function countBrand($brand_id, $brand_name) {
$sql = "SELECT brand FROM coupons WHERE expire >= CURRENT_DATE AND brand='".$brand_id."'";
$result = mysql_query($sql) || die (mysql_error()); // always check for errors
list($brand) = mysql_fetch_row($result);
// fetch row, returns a more concise array then mysql_fetch_array
// $row = mysql_fetch_array($result);
// use commas rather then . when concatenating echo statements
// dots force concatenation before output
echo '<li>',$brand,'</li>';
}
function brandCount() {
$sql = "SELECT DISTINCT brand,brand_id,brand_name FROM coupons,coupons_brand WHERE brand=brand_id AND expire >= CURRENT_DATE ORDER BY brand_name";
$result = mysql_query($sql) || die(mysql_error()); // always check for errors
// $row = mysql_fetch_array($result); // not sure why this is needed
$num = mysql_num_rows($result);
// use commas rather then . when concatenating echo statements
// dots force concatenation before output
echo '<h3>',$num,' Brands</h3>';
echo '<ul>';
// fetch all cols at once, rather then using lots of separate calls to mysql_result
// use mysql_fetch_row as it returns just the ordered values (vs mysql_fetch_assoc, and mysql_fetch_array)
//
while(list($brand, $brand_id, $brand_name) == mysql_fetch_row($result)) {
countBrand($brand_id, $brand_name);
}
// replaced with while loop above
// $i = 0;
// while ($i < $num) {
// $brand_id = mysql_result($result, $i, "brand_id");
// $brand_name = mysql_result($result, $i, "brand_name");
// countBrand($brand_id, $brand_name);
// $i++;
}
echo '</ul>';
}
those enhancements will only give you a minor speed increase
the biggest speed increase you will get is if you call the database less.
currently you select each brand, and then go back and count each brand individually
without knowing the structure of you tables this sql is difficult for me to write, so it is a guess, but it should point you in the right direction
SELECT brand, brand_id, brand_name, COUNT(*) as brandcount
FROM coupons
JOIN coupons_brand ON brand=brand_id
WHERE expire >= CURRENT_DATE
GROUP BY brand, brand_id, brand_name
ORDER BY brand_name
mysql_fetch_array($result,MYSQL_ASSOC);
SELECT SQL_CACHE brand FROM
Profiling query

How can I query the mysql database for a variable, if exists create another variable, if not insert?

say I have a variable
$id = mt_rand();
how can I query the mysql database to see if the variable exists in the row id, if it does exist then change the variable $id, once the variable is unique to all other stored ids, then insert it into the database?
Thanks you guys.
$con = mysql_connect("<host>","<login>","<pass>");
if ($con) {
mysql_select_db('<schemata>', $con);
$found = false;
while (!$found) {
$idIamSearching = mt_rand();
$query = mysql_query("SELECT count(*) FROM <table> WHERE <idColumnName>='".$idIamSearching."'");
$result = mysql_fetch_row($query);
if ($result[0] > 0) {
mysql_query("INSERT INTO <table> (<column>) VALUES ('".$idIamSearching."')");
$found = true;
}
}
mysql_close($con);
}
Your description is hard to understand, so, this is something that could give you pointers...
'SELECT COUNT(*) as count from table where row_id="'.$variable.'" LIMIT 1'
make sure to escape the variable if it's user input or if it's going to have more than alphanumeric characters
then fetch the row and check if count is 1 or greater than 0
if one, then it exists and try again (in a loop)
although, auto increment on the id field would allow you to avoid this step
$bExists = 0;
while(!$bExists){
// Randomly generate id variable
$result = mysql_query("SELECT * FROM table WHERE id=$id");
if($result){
if(mysql_num_rows($result) > 0){
$bExists = 1;
} else {
// Insert into database
$bExists = 1;
}
}
1 Randomly generate id variable
2 Query database for it
2.1 Result? exit
2.2 No result? Insert

Categories