Unexpected variable scope in PHP - php

I would like to show 3 random images from database in my website. Below is its code:
$query = mysql_query ("SELECT id,url FROM tbl_gallery2");
if (mysql_num_rows($query) >= 3) {
$my_array = array();
$last_array = array();
while ($r = mysql_fetch_row($query)) {
$my_array[] = $r[1];
}
function makernd () {
$number = array_rand($my_array,1);
if (in_array($number,$last_array)) {
makernd();
} else {
$last_array[] = $number;
return $number;
}
}
for($i = 1 ; $i < 3 ; $i++) {
$item = makernd();
echo '<img src="./images/slider/'.$item.'.jpg" alt="" class="slider" />';
}
}
But whenever I run this code, I get the error below:
Undefined variable: my_array in line ... // The first line of makernd() function.
But I expected $my_array to be an accessible array for this function.
What's the problem?

To simply fix your problem, you should pass $my_array to makernd() as a parameter:
$query = mysql_query ("SELECT id,url FROM tbl_gallery2");
if (mysql_num_rows($query) >= 3) {
$my_array = array();
$last_array = array();
while ($r = mysql_fetch_row($query)) {
$my_array[] = $r[1];
}
function makernd ($my_array) {
$number = array_rand($my_array,1);
if (in_array($number,$last_array)) {
makernd($my_array);
} else {
$last_array[] = $number;
return $number;
}
}
for($i = 1 ; $i < 3 ; $i++) {
$item = makernd($my_array);
echo '<img src="./images/slider/'.$item.'.jpg" alt="" class="slider" />';
}
}
HOWEVER, I strongly suggest putting the randomization in MySQL, to
Simplify your code
Significantly improve the performance, and
Eliminate excessive loops & recursion in PHP
Example:
$sql = "SELECT id,url
FROM tbl_gallery2
ORDER BY RAND()
LIMIT 3";
$query = mysql_query ($sql);
if (mysql_num_rows($query) >= 3) {
while ($r = mysql_fetch_row($query)) {
echo '<img src="./images/slider/' . $r[1] . '.jpg" alt="" class="slider" />';
}
}
PS - I also suggest you update your code to use mysqli, as mysql is deprecated
PPS - I also suggest you look into mysqli_fetch_assoc so you can reference query results by name instead of index (e.g. $r['url'] instead of $r[1] - as if you ever change the order of your query, you will break references by index.

Related

PHP if random code exists in database regenerate random code

I'm attempting to create a PHP script that will create a random code and check it against a database to see if it exists. I'd like it to check that if it exists then generate another createRandomCode() and check it.
Unsure how to proceed with looping until the number of rows are 0.
function createRandomCode($length='6'){
$chars = "abcdefghijkmnopqrstuvwxyz023456789";
srand((double)microtime()*1000000);
$i = 0;
$code= '';
while ($i++ < $length){
$code = $code. substr($chars, rand() % 33, 1);
}
return $code;
}
$shorturl = createRandomCode();
$q = $db - > query("SELECT * FROM maps WHERE url='".$shorturl.
"'");
if (mysqli_num_rows($q) > 0) {
$arr = json_encode($arr);
echo $arr;
}
Sounds like a good candidate for a do...while loop:
do {
$shorturl = createRandomCode();
$q = $db->query("SELECT * FROM maps WHERE url='".$shorturl."'");
} while(mysqli_num_rows($q) > 0);
function regenerateCode(){
global $connection;
do{
$serial2 = rand(0,7);
$check_code = "SELECT * FROM `voters` WHERE `serial` = '$serial2'";
$run_check_code = mysqli_query($connection,$check_code);
$count = mysqli_num_rows($run_check_code);
} while( $count > 0 );
return $serial2;
}

mysql_fetch_array is including previous value in next one

I used this same code before and not like that just for one image at one time it is working fine there for showing img(stars)but now stars in first value is fine next it is collecting result with previous one
while ($query = mysql_fetch_array($tableone))
{
$Rating = $query['rating'];
$totalV = $query['total_votes'];
$commentcount = $query['comment_counts'];
if (!$Rating == 0 )
{
$number = $Rating / $totalV ;
$numbers = (round($number,3));
for ($x = 1 ; $x <= $numbers ; $x++)
{
$star .= '<img src="img/stars.gif" width="14%"/>';
}
$left = 5 - $numbers ;
for ($x = 1 ; $x <= $left ; $x++)
{
$result .='<img src="img/whitestar.gif" width="12%"/>';
}
if ( strpos($left, '.' ) == true)
{
$hs .= '<img src="img/halfwhitestar.gif" width="12%"/>';
}
$result1 = $star. $hs .$result;
}
else
{
$result1 ='Null';
}
if (empty($totalV))
{
$totalV = 'No votes';
}
$totalV ="/".$totalV;
$ratingbox = "<span id=\"ratingimg\">".$result1." </span>
<br/>
<span class=\"valueimg\">".$number.$totalV."</span>";
}
my Values in database of each image is
and this code is visible like this
this code i am using now for table for all images present in database including their some information...need guidance:S
Since you are concatenating strings during your loop, those strings just keep growing with each iteration of the loop.
I suggest that you reset these variables to blank strings upon each iteration of your while loop: $star, $hs, $result.
Something like this:
while ($query = mysql_fetch_array($tableone)) {
$star=$hs=$result='';
...

Use for loop to incrementally select values from MySQL query

I am trying to use a for loop to select an incremental value with a MySQL query. I have included sample code below:
<?php
$day_1="sep_28";
$day_2="sep_29";
$day_3="sep_30";
$query = mysql_query("SELECT * FROM table WHERE id = '$id'");
while ($row = mysql_fetch_assoc($query))
{
for ($i = 1; $i <= 3; $i++)
{
$dayVar = "day_".$i;
//$dayVarCount = $dayVar."_count"; // Don't really need this anymore, so removed.
$dayVarCount = $row[$$dayVar];
echo "$$dayVar.': '.$dayVarCount<p>"; // Edited.
}
}
?>
I think I am getting close, but when I run the code my page is showing this:
$day_1.': '.0
$day_2.': '.2
$day_3.': '.5
Any additional recommendations? Thanks for the great help!
Try a variable variable:
for ($i = 1; $i <= 3; $i++)
{
$dayVar = "day_".$i;
$dayVarCount = $dayVar."_count";
$$dayVarCount = $row[$$dayVar];
echo $$dayVar.': '.$$dayVarCount.'<p>'; // Edited.
}
This basically uses a string to reference a variable by its name.
Just think of it this way:
$variable = 'hello';
$string = 'variable';
echo $$string;
// Is the same thing as:
echo $variable;
// Because you can thing of $$string as ${$string} ---> $variable when {$string} is interpreted into 'variable'
http://php.net/manual/en/language.variables.variable.php
Replace this line:
echo "$$dayVar.': '.$dayVarCount<p>";
with this:
echo $$dayVar . ': ' . $dayVarCount . '<br>';
<?php
$day_1="January 1";
$day_2="January 2";
$day_3="January 3";
$query = mysql_query("SELECT * FROM dates WHERE id = '$id'");
while ($row = mysql_fetch_assoc($query))
{
for ($i = 1; $i <= 3; $i++)
{
$var = $."day_".$i;
$day_$i_count=$row['$var'];
echo "$day_$i: $day_$i_count<p>";
}
}
?>
You can try this code too.
That all seems overly complicated, but possibly I don't understand the question adequately. Would this work?
$day[1]="sep_28";
$day[2]="sep_29";
$day[3]="sep_30";
$query = mysql_query("SELECT * FROM table WHERE id = '$id'");
while ($row = mysql_fetch_assoc($query))
{
foreach ($day as $day_str)
{
echo $day_str . ':' . $row[$day_str] . '<p>';
}
}

variable increment doesn't work

When I launch my web page, increment doesn't work correctly!
It should go like this: $i = from 1 to x (0,1,2,3,4,5,6 etc..).
But instead it jumps over every step giving result of (1,3,5,7 etc..).
Why is this code doing this?
<ul class="about">
<?php
$result = mysql_query("SELECT * FROM info WHERE id = 1");
while ($row = mysql_fetch_assoc($result))
{
$bioText = $row['bio'];
}
$endBioTxt = explode("\n", $bioText);
for ($i=0; $i < count($endBioTxt);)
{
if (checkNum($i) == true)
{
echo "<li class='left'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
else
{
echo "<li class='right'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
$i++;
}
// Function to check if number is prime
function checkNum($num){
return ($num % 2) ? TRUE : FALSE;
}
?>
</ul>
Output:
Sometext!(right side)
0
1
Sometext2!(right side)
2
3
...
Please DONT do this as other suggested:
for ($i=0; $i < count($endBioTxt); $i++)
do this:
$count = count($endBioTxt);
for ($i=0; $i < $count; $i++) {
}
No need to calculate the count every iteration.
Nacereddine was correct though about the fact that you don't need to do:
$i++;
inside your loop since the preferred (correct?) syntax is doing it in your loop call.
EDIT
You code just looks 'strange' to me.
Why are you doing:
while ($row = mysql_fetch_assoc($result))
{
$bioText = $row['bio'];
}
???
That would just set $bioText with the last record (bio value) in the recordset.
EDIT 2
Also I don't think you really need a function to calculate the modulo of a number.
EDIT 3
If I understand your answer correctly you want 0 to be in the left li and 1 in the right li 2 in the left again and so on.
This should do it:
$endBioTxt = explode("\n", $bioText);
$i = 0;
foreach ($endBioTxt as $txt)
{
$class = 'left';
if ($i%2 == 1) {
$class = 'right';
}
echo '<li class="'.$class.'"><div>'.$txt.'</div></li>';
echo $i; // no idea why you want to do this since it would be invalid html
$i++;
}
Your for statement should be:
for ($i=0; $i < count($endBioTxt); $i++)
see http://us.php.net/manual/en/control-structures.for.php
$i++; You don't need this line inside a for loop, it's withing the for loop declaration that you should put it.
for ($i=0; $i < count($endBioTxt);$i++)
{
if (checkNum($i) == true)
{
echo "<li class='left'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
else
{
echo "<li class='right'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
//$i++; You don't need this line inside a for loop otherwise $i will be incremented twice
}
Edit: Unrelated but this isn't how you check whether a number is prime or not
// Function to check if number is prime
function checkNum($num){
return ($num % 2) ? TRUE : FALSE;
}
This code works, please test it in your environment and then uncomment/comment what you need.
<?php
// This is how query should look like, not big fan of PHP but as far as I remember...
/*
$result = mysql_query("SELECT * FROM info WHERE id = 1");
$row = mysql_fetch_assoc($result);
$bioText = $row['bio'];
$endBioTxt = explode("\n", $bioText);
*/
$endBioTxt[0] = "one";
$endBioTxt[1] = "two";
$endBioTxt[2] = "three";
$endBioTxt[3] = "four";
$endBioTxt[4] = "five";
$totalElements = count($endBioTxt);
for ($i = 0; $i < $totalElements; $i++)
{
if ($i % 2)
{
echo "<li class='left'><div>".$endBioTxt[$i]."</div></li>";
}
else
{
echo "<li class='right'><div>".$endBioTxt[$i]."</div></li>";
}
/*
// This is how you should test if all your array elements are set
if (isset($endBioTxt[$i]) == false)
{
echo "Array has some values that are not set...";
}
*/
}
Edit 1
Try using $endBioTxt = preg_split('/$\R?^/m', $bioTxt); instead of explode.

Select lowest price from database row and ignore null or 0

I have a database called prices and there are 12 columns lets say.
comp1, comp2, comp3, comp4, comp5, comp6 and so on.
I then want to run a query to find the lowest price stored in that row that matches an id, however I think it is treating null as lowest value as I am not getting the correct answer.
Anyway around this? or am i doing this wrong?
$query = "SELECT * FROM Prices WHERE id =$id" or die(mysql_error());
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$comp1= $row['comp1'];
$comp2= $row['comp2'];
$comp3= $row['comp3'];
$comp4= $row['comp4'];
$comp5= $row['comp5'];
$comp6= $row['comp6'];
$comp7= $row['comp7'];
$comp8= $row['comp8'];
$comp9= $row['comp9'];
$comp10= $row['comp10'];
$comp11= $row['comp11'];
$comp12= $row['comp12'];
$min = array( $comp1, $comp2, $comp3, $comp4, $comp5, $comp6, $comp7, $comp8, $comp8, $comp10, $comp11, $comp12);
echo min($min);
}
If you call array_filter() on the array before calling min(), you will purge anything that evaluates to false, including null and 0.
For example: $min = min(array_filter($min));
Try:
$min = array( $comp1, $comp2, $comp3, $comp4, $comp5, $comp6, $comp7, $comp8, $comp8, $comp10, $comp11, $comp12);
$min = array_filter($min);
echo min($min);
From a comment in http://php.net/manual/en/function.min.php:
I've modified the bugfree min-version to ignore NULL values (else it returns 0).
<?php
function min_mod () {
$args = func_get_args();
if (!count($args[0])) return false;
else {
$min = false;
foreach ($args[0] AS $value) {
if (is_numeric($value)) {
$curval = floatval($value);
if ($curval < $min || $min === false) $min = $curval;
}
}
}
return $min;
}
?>
Try this:
$query = "SELECT * FROM Prices WHERE id =$id" or die(mysql_error());
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$i= 0;
foreach ($row as $val) {
if ($i == 0) {
$tmpMin = $val;
} else {
if ($tmpMin < $val) {
$val = $tmpMin;
}
}
}
unset($tmpMin);
echo $tmpMin;
}

Categories