Undefined variable if count 0 - php

i have a little bit problem with my following code. I am trying to make a star raiting system and following code is showing raiting details. But i am getting
undefined variable rate_db notice
from if(count($rate_db)) What i missing here anyone can tell me please ?
full code is here:
<?php
$query = mysqli_query($db,"SELECT ryid,r_type FROM profileRaiting WHERE rp_uid='$profile_uid'");
while($data = mysqli_fetch_assoc($query)){
$rate_db[] = $data;
$sum_rates[] = $data['r_type'];
}
if(count($rate_db)){
$rate_times = count($rate_db);
$sum_rates = array_sum($sum_rates);
$rate_value = $sum_rates/$rate_times;
$rate_bg = (($rate_value)/5)*100;
} else {
$rate_times = 0;
$rate_value = 0;
$rate_bg = 0;
}
?>

It's better to initialize your both arrays at top as:
$rate_db = array();
$sum_rates = array();
And i don't know where you define this variable $profile_uid, if it's user input or session value, than your code is open for SQL Injection, you can use Prepared Statement to prevent SQL attack. And this post will help you to understand: How can I prevent SQL injection in PHP?
Side Note & Suggestion:
One more thing, you can also get the sum of r_type as:
$sum_rates += $data['r_type'];
In this case, you need to initialize $sum_rates as:
$sum_rates = 0;
And just remove this line from IF condition:
$sum_rates = array_sum($sum_rates);
Benefit, no need to use extra method.

$rate_db variable is defined in the while loop where you fetch the data from MySQL. However, if the query does not return any records, then while loop's body will not be executed, thus $rate_db variable will not be defined.
Solution: define $rate_db variable as an empty array before the while loop.

You can initialize the variable:
<?php
$rate_db = array();
$sum_rates = array();
$query = mysqli_query($db,"SELECT ryid,r_type FROM profileRaiting WHERE rp_uid='$profile_uid'");
while($data = mysqli_fetch_assoc($query)){
$rate_db[] = $data;
$sum_rates[] = $data['r_type'];
}
$rate_times = count($rate_db);
if($rate_times > 0){
$sum_rates = array_sum($sum_rates);
$rate_value = $sum_rates/$rate_times;
$rate_bg = (($rate_value)/5)*100;
} else {
$rate_times = 0;
$rate_value = 0;
$rate_bg = 0;
}
?>

before using count you need to be sure that it does have something in it so your complete code can be like this
<?php
$query = mysqli_query($db,"SELECT ryid,r_type FROM profileRaiting WHERE rp_uid='$profile_uid'");
while($data = mysqli_fetch_assoc($query)){
$rate_db[] = $data;
$sum_rates[] = $data['r_type'];
}
if(isset($rate_db) && count($rate_db)){
$rate_times = count($rate_db);
$sum_rates = array_sum($sum_rates);
$rate_value = $sum_rates/$rate_times;
$rate_bg = (($rate_value)/5)*100;
} else {
$rate_times = 0;
$rate_value = 0;
$rate_bg = 0;
}
?>

$query = mysqli_query($db,"SELECT ryid,r_type FROM profileRaiting WHERE rp_uid='$profile_uid'");
while($data = mysqli_fetch_assoc($query)){
$rate_db[] = $data;
$sum_rates[] = $data['r_type'];
}
Because when your query returns empty result the while loop will never become true, so $rate_db[] will never be reached and therefore will never be created.
to fix this, you should declare $rate_db[] as empty first at the top of your script. to avoid the error.

Related

Remove certain String from array php

I want to get rid of that string with help of the str_replace function in PHP but I won't work. Can anybody help me?
$sql = "SELECT data from users";
$result = $mysqli->query($sql);
$widgets = [];
while($row = mysqli_fetch_array($result))
{
$widgets[] = $row;
}
$alignment = explode("//",serialize($widgets));
for($i = 0; $i<count($alignment); $i++){
str_replace("a:3:{i:0,:a:2:{:i:0;s:31;q}")
}
?>
As said in http://php.net/manual/en/function.str-replace.php
php_replace take 3 arguments
$replaced = str_replace(search, replaced_by, initial_string, [&replaced]);
Refer str_replace function for clarity, and change your code like below:
$replacedValue = str_replace("a:3:{i:0,:a:2:{:i:0;s:31;q}","",$alignment[$i]);

How to use variable from a while, but outside the while?

I have this:
$nome='x.png';
if(file_exists('../../images/produtos/'.$nome)){
$i = 1;
while(file_exists('../../images/produtos/'.$i."_".$nome))
{
$i++;
}
$nome = $i."_".$nome;
}
and then i need to put the variable $nome into a mysql_query, just like this
mysql_query("INSERT INTO produtos (nome) VALUES ('$nome)");
but it doesnt show the 'edited' variable.
As noted in the answer to the following Stackoverflow post by #PhpXp, you could try to define the variable before the while loop. See below:
$report = "";
while ($row = mysql_fetch_array($result)) {
$report += "a"."b".$row["prevDOCid"]+1;
}
echo $report;

PHP to be checked using for and while

I have the following code which does not seem to be working. As far as i can tell the predefined arrays are each of the same size - i have 32 rows in my table "homepage" where "username", "image" and "website" are three fields. For testing purposes the usernames are 1 to 32. And the image and website fields are blank - at the moment (this will change).
The code i have is:
$sorthpge = mysql_query ("SELECT * FROM homepage ORDER BY no DESC LIMIT 32");
$links = array();
$images = array();
$usern = array();
$array_Length_1 = count($usern);
for ($i=0; $i<$array_Length_1; $i++)
{
while ($row_1 = mysql_fetch_assoc ($sorthpge)) {
$images[$i] = $row_1['image'];
$links[$i] = $row_1['website'];
$usern[$i] = $row_1['username'];
if($images[$i] == ""){
$images[$i] = "uploads/default.png";
$links[$i] = "register.php?no=";
}
else
{
if($images[$i] == "auction"){
$images [$i] = "uploads/auction.png";
$links[$i] = "auction.php?no=";
}
}
}
}
You can probably tell what i'm trying to do. As mentioned all the "image" rows are blank so i should be getting "$images[i] = "uploads/default.png" for all i up to 32. But nothing is showing in my html.
Just wondered if somebody could point out an error in my code. Or if my set up assumes something wrong. I'm pretty new to php. Thanks a lot in advance. P.S i will translate to mysqli when i can get these basics working.
If this is all the code, this is the problem:
$usern = array();
$array_Length_1 = count($usern);
for ($i=0; $i<$array_Length_1; $i++)
{
The array is empty, so the length is 0 so your code will never run.
What is the purpose of that for loop anyway? It seems you can just remove it.
In your sample code, you have the following:
$usern = array();
$array_Length_1 = count($usern);
for ($i=0; $i<$array_Length_1; $i++) {
As $usern is empty, $array_Length_1 is 0 - your loop is never executed.
I'm not sure what your logic behind doing this was/is, so I don't know a proper way to suggest to fix it, however, if you were to remove the for loop entirely and store a separate incrementer, $i, the code should work fine.
For instance, try updating your code to the following:
$sorthpge = mysql_query ("SELECT * FROM homepage ORDER BY no DESC LIMIT 32");
$links = array();
$images = array();
$usern = array();
$i = 0;
while ($row_1 = mysql_fetch_assoc ($sorthpge)) {
$images[$i] = $row_1['image'];
$links[$i] = $row_1['website'];
$usern[$i] = $row_1['username'];
if($images[$i] == ""){
$images[$i] = "uploads/default.png";
$links[$i] = "register.php?no=";
} else if($images[$i] == "auction"){
$images [$i] = "uploads/auction.png";
$links[$i] = "auction.php?no=";
}
$i++;
}
$array_Length_1 = count($usern);
Is you problem ! Array is empty since you just declared it
One problem is that $array_Length_1 = count($usern); Your array $usern is empty.And you for loop max value is empty. meaning that $i is incrementing to 0.
$usern = array();
$array_Length_1 = count($usern);
for ($i=0; $i<$array_Length_1; $i++)
And make sure your file is saved as a php file as you mentioned your html file is showing nothing.
Your above code was failing in a few places I think. This $array_Length_1 = count($usern); wasn't helping. The for loop was running off the count of the $array_length, which was always going to be empty because it hadn't been filled yet...
Give this a try:
<?php
// connection strings here or db include
$sorthpge = mysql_query ("SELECT * FROM homepage ORDER BY no DESC");
$links = array();
$images = array();
$usern = array();
$array_Length_1 = count($usern);
$i = 0;
while ($row_1 = mysql_fetch_assoc($sorthpge)){
$images[$i] = $row_1['image'];
$links[$i] = $row_1['website'];
$usern[$i] = $row_1['username'];
if($row_1['image'] == ""){
$images[$i] = "uploads/default.png";
$links[$i] = "register.php?no=";
}
elseif($row_1['image'] == "auction"){
$images [$i] = "uploads/auction.png";
$links[$i] = "auction.php?no=";
}
$i++;
}
?>

Formatting information in a PHP recordset and setting it to an Array

I am attempting to use a Manager Class to take the results of a query and do formatting on pieces of information so I don't have to have logic on my view. I googled a number of solution and thought this would work, but my Array of Key=>values is coming back blank. Can someone take a look at it and see what i am doing wrong? Thanks!
I have verified that $results contains the values I am attempting to format and place back into an Array.
while($row = mysqli_fetch_array($results)){
$pets[$row['petID']] = $row['petID'];
$pets[$row['chipID']]=$row['chipID'];
$pets[$row['adoptionDate']]=Date($row['adoptionDate'],'m-d-Y');
$pets[$row['pType']]=$row['pType'];
$pets[$row['breedName2']]=$row['breedName2'];
$pets[$row['breedName1']]=$row['breedName1'];
$pets[$row['imageName']]=$row['imageName'];
$pets[$row['intakeDate']]= Date($row['intakeDate'],'m-d-Y');
$pets[$row['status']]=$row['status'];
$pets[$row['age']]=$row['age'];
$pets[$row['ageText']]= $this->getAge($row['age']);
$pets[$row['gender']]=$row['gender'];
$pets[$row['genderText']] = $this->getGender($row['gender']);
$pets[$row['breed2']]=$row['breed2'];
$pets[$row['breed']]=$row['breed'];
$pets[$row['petType']]=$row['petType'];
$pets[$row['petName']]=$row['petName'];
$pets[$row['customID']]=$row['customID'];
}
Here is the complete function that does not return anything:
public function getPets($cond,$orgID){
$pets = array();
$pg = new petsGateway();
$results = $pg->listByQuery($cond, $orgID);
while($row = mysqli_fetch_array($results)){
$pets[$row['petID']] = $row['petID'];
$pets[$row['chipID']]=$row['chipID'];
$pets[$row['adoptionDate']]=Date($row['adoptionDate'],'m-d-Y');
$pets[$row['pType']]=$row['pType'];
$pets[$row['breedName2']]=$row['breedName2'];
$pets[$row['breedName1']]=$row['breedName1'];
$pets[$row['imageName']]= $this->getImageURL($row['imageName']);
$pets[$row['intakeDate']]= Date($row['intakeDate'],'m-d-Y');
$pets[$row['status']]=$row['status'];
$pets[$row['age']]=$row['age'];
$pets[$row['ageText']]= $this->getAge($row['age']);
$pets[$row['gender']]=$row['gender'];
$pets[$row['genderText']] = $this->getGender($row['gender']);
$pets[$row['breed2']]=$row['breed2'];
$pets[$row['breed']]=$row['breed'];
$pets[$row['petType']]=$row['petType'];
$pets[$row['petName']]=$row['petName'];
$pets[$row['customID']]=$row['customID'];
}
return $pets;
}
That's rather... repetitive code... wouldn't it be easier to modify your query to fetch the rows you want AND do the date formatting directly in the DB?
e.g.
SELECT rowID, ... DATE_FORMAT(adoptionDate, '%m-%d-%Y'), ...
FROM ...
and then
while($row = mysql_fetch_assoc($result)) {
$pets[] = $row;
}
hm.... well im not sure what you want, but as you have it now, the key and the value of your array will be the same, which makes it useless.
i.e. for petName
$pets['Fido'] = 'Fido'
probably you want to get rid of the $row portion of the left side of your assignment, so that you end up with this
while($row = mysqli_fetch_array($results))
{
$pet = Array();
$pet['petID'] = $row['petID'];
$pet['chipID'] = $row['chipID'];
$pet['adoptionDate'] = Date($row['adoptionDate'],'m-d-Y');
$pet['pType'] = $row['pType'];
$pet['breedName2'] = $row['breedName2'];
$pet['breedName1'] = $row['breedName1'];
$pet['imageName'] = $row['imageName'];
$pet['intakeDate'] = Date($row['intakeDate'],'m-d-Y');
$pet['status'] = $row['status'];
$pet['age'] = $row['age'];
$pet['ageText'] = $this->getAge($row['age']);
$pet['gender'] = $row['gender'];
$pet['genderText'] = $this->getGender($row['gender']);
$pet['breed2'] = $row['breed2'];
$pet['breed'] = $row['breed'];
$pet['petType'] = $row['petType'];
$pet['petName'] = $row['petName'];
$pet['customID'] = $row['customID'];
$pets.push($pet);
}
I am guessing but I understood that you want some thing like:
while($row = mysqli_fetch_array($results)){
$pets[$row['petID']]['petID'] = $row['petID'];
$pets[$row['petID']]['chipID'] = $row['chipID'];
$pets[$row['petID']]['adoptionDate'] = Date($row['adoptionDate'],'m-d-Y');
$pets[$row['petID']]['pType'] = $row['pType'];
$pets[$row['petID']]['breedName2'] = $row['breedName2'];
$pets[$row['petID']]['breedName1'] = $row['breedName1'];
$pets[$row['petID']]['imageName'] = $row['imageName'];
$pets[$row['petID']]['intakeDate'] = Date($row['intakeDate'],'m-d-Y');
$pets[$row['petID']]['status'] = $row['status'];
$pets[$row['petID']]['age'] = $row['age'];
$pets[$row['petID']]['ageText'] = $this->getAge($row['age']);
$pets[$row['petID']]['gender'] = $row['gender'];
$pets[$row['petID']]['genderText'] = $this->getGender($row['gender']);
$pets[$row['petID']]['breed2'] = $row['breed2'];
$pets[$row['petID']]['breed'] = $row['breed'];
$pets[$row['petID']]['petType'] = $row['petType'];
$pets[$row['petID']]['petName'] = $row['petName'];
$pets[$row['petID']]['customID'] = $row['customID'];
}
This way you have an array with all the pets ID as first key and its details in the second key. You can use the array push as well.
That will rewrite $pets[KEY] each time it loops through record. You want..
$pets[]['petID'] = $row['petID'];
$pets[]['chipID'] = $row['chipID'];
and so on

Create new variable to store each result during While loop

I have a while loop that loops through 3 results and echo's these out in a list. It will always be 3 results.
Here is my current PHP:
while($row = sqlsrv_fetch_array($res))
{
echo "<li>".$row['SessionValue']."</li>";
// prefer to store each value in its own variable
}
However I'd like to store the $row['SessionValue'] value in each loop in a new variable.
So....
first loop: $i0 = $row['SessionValue'];
second loop: $i1 = $row['SessionValue'];
third loop: $i2 = $row['SessionValue'];
How would I achieve this with PHP?
Many thanks for any pointers.
$lst_count = array();
while($row = sqlsrv_fetch_array($res))
$lst_count[] = $row["SessionValue"];
You just need another variable that gets incremented:
$count = 0;
while($row = sqlsrv_fetch_array($res))
{
${i.$count++} = $row['SessionValue'];
}
You can do this have SUM of all value:
$total = array();
while($row = sqlsrv_fetch_array($res))
{
$total[] = $row["SessionValue"]
} $sumAll = array_sum($total);

Categories