PHP to be checked using for and while - php

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++;
}
?>

Related

Undefined variable if count 0

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.

Re-usable PDO query function to multidimansional array

I'm trying to build a re-usable function to multidimansional array for every tablename i put in.
Like most i start mine tables whit ID and want to start the array whit that id, so not start whit 0 :) . foneticly--> $my_array[id]["email"]
So to build it i thought "what do i need" and found : $count_colum, $total_row an ofcource the data itself.
I know how to build a array, but i dont know how to build a "variable" array.
I also know i cant use PHP inside a array :) (whish would help iff you tell me)
$my_array = array( $row['id'] for ($i = 0; $i < $count_colum; $i++){...}
I also hope somebody knows what i mean :) I'm a little bit new to this all ;)
This is what i get this far:
function make_MDA($tablename)
{
$dbh = new PDO("mysql:host='localhost';dbname='dbname', 'usr','pas'");
$query = $dbh->prepare("SELECT * FROM `".$tablename."`");
$query->execute();
$count_colum = $query->columnCount();
$result = $query->fetchAll();
$total_row = count($result);
for ($i = 0; $i < $count_colum; $i++)
{
$meta = $query->getColumnMeta($i);
$column[] = $meta['name'];
}
foreach ($result as $row)
{
$my_array = array( $row['id'] //this is where I'm stuck
}
// echo $column[3];
// echo $total_row;
// echo $count_colum;
}
This should work, don't overcomplicate things:
function make_MDA($tablename)
{
$dbh = new PDO("mysql:host='localhost';dbname='dbname', 'usr','pas'");
$query = $dbh->prepare("SELECT * FROM `".$tablename."`");
$query->execute();
$result = $query->fetchAll();
foreach ($result as $row)
{
$id = $row['id'];
$my_array[$id] = $row;
}
return $my_array;
}
I would make the connection to the database $dbh once outside this function.

PHP Array & XML Can't get all content

I'm tring to get all content from this xml: https://api.eveonline.com/eve/SkillTree.xml.aspx
To save it on a MySQL DB.
But there are some data missing...
Could any1 that understand PHP, Array() and XML help me, please?
This is my code to get the content:
<?php
$filename = 'https://api.eveonline.com/eve/SkillTree.xml.aspx';
$xmlbalance = simplexml_load_file($filename);
$skills = array();
for ($x=0;$x<sizeOf($xmlbalance->result->rowset->row);$x++) {
$groupName = $xmlbalance->result->rowset->row[$x]->attributes()->groupName;
$groupID = $xmlbalance->result->rowset->row[$x]->attributes()->groupID;
for ($y=0;$y<sizeOf($xmlbalance->result->rowset->row[$x]->rowset->row);$y++) {
$skills[$x]["skillID"] = "".$xmlbalance->result->rowset->row[$x]->rowset->row[$y]->attributes()->typeID;
$skills[$x]["skillName"] = "".$xmlbalance->result->rowset->row[$x]->rowset->row[$y]->attributes()->typeName;
$skills[$x]["skillDesc"] = "".$xmlbalance->result->rowset->row[$x]->rowset->row[$y]->description;
$skills[$x]["skillRank"] = "".$xmlbalance->result->rowset->row[$x]->rowset->row[$y]->rank;
$skills[$x]["skillPrimaryAtr"] = "".$xmlbalance->result->rowset->row[$x]->rowset->row[$y]->requiredAttributes->primaryAttribute;
$skills[$x]["skillSecondAtr"] = "".$xmlbalance->result->rowset->row[$x]->rowset->row[$y]->requiredAttributes->secondaryAttribute;
$o = 0;
for ($z=0;$z<sizeOf($xmlbalance->result->rowset->row[$x]->rowset->row[$y]->rowset->row);$z++) {
if ($xmlbalance->result->rowset->row[$x]->rowset->row[$y]->rowset->attributes()->name == "requiredSkills") {
$skills[$x]["requiredSkills"]["".$xmlbalance->result->rowset->row[$x]->rowset->row[$y]->rowset->row[$z]->attributes()->typeID] = "".$xmlbalance->result->rowset->row[$x]->rowset->row[$y]->rowset->row[$z]->attributes()->skillLevel;
$o++;
}
}
}
}
echo '<pre>'; print_r($skills); echo '</pre>';
?>
If you go to the original XML (link), at line 452, you will see:
<row groupName="Spaceship Command" groupID="257">
And that isn't show in my array (link)...
That is one thing that i found that is missing...
I think that probally have more content that is missing too..
Why? How to fix it, please?
Thank you!!!
You will only get a total of sizeof($xmlbalance->result->rowset->row) records. Because, in your 2nd for loop, you are basically storing your result in the same array element that is $skills[$x].
Try this (I also higly encourage you to be as lazy as you can when you write code - by lazy I mean, avoid repeating / rewriting the same code over and over if possible) :
$filename = 'https://api.eveonline.com/eve/SkillTree.xml.aspx';
$xmlbalance = simplexml_load_file($filename);
$skills = array();
foreach ($xmlbalance->result->rowset->row as $row)
{
$groupName = $row->attributes()->groupName;
$groupID = $row->attributes()->groupID;
foreach ($row->rowset->row as $subRow)
{
$skill['skillID'] = (string) $subRow->attributes()->typeID;
$skill['skillName'] = (string) $subRow->attributes()->typeName;
$skill['skillDesc'] = (string) $subRow->description;
$skill['skillRank'] = (string) $subRow->rank;
$skill['skillPrimaryAtr'] = (string) $subRow->requiredAttributes->primaryAttribute;
$skill['skillSecondAtr'] = (string) $subRow->requiredAttributes->secondaryAttribute;
foreach ($subRow->rowset as $subSubRowset)
{
if ($subSubRowset->attributes()->name == 'requiredSkills')
{
foreach ($subSubRowset->row as $requiredSkill)
{
$skill['requiredSkills'][(string) $requiredSkill->attributes()->typeID] = (string) $requiredSkill['skillLevel'];
}
}
}
$skills[] = $skill;
}
}
print_r($skills);

PHP code to be checked

I have the following code. What I have labelled block 1 and block 2 don't seem to work together but one does if i get rid of the other; when checking using print_r. I am fairly new to php and was wondering if somebody could point out where I went wrong. I had it working somewhere else before but lost the file. Many thanks in advance.
P.S: I am aware it is a good idea to get into PDO and mysqli sooner rather than later. But I just want to get to grips with the basics first.
<?php
//Connect to database
$connect = mysql_connect ("localhost","root","password");
$db = mysql_select_db("project");
//Find top 100 most popular images
$pop = mysql_query("
SELECT * FROM users ORDER BY pop DESC LIMIT 2
");
//Define local variables for images to show
//block 1//
$images = array();
while ($row = mysql_fetch_array($pop)) {
$images[] = $row['image'];
}
//block2//
$links = array ();
while ($row = mysql_fetch_array($pop)){
$links[] = $row['username'];
}
?>
mysql_data_seek will work:
$images = array();
while ($row = mysql_fetch_array($pop)) {
$images[] = $row['image'];
}
mysql_data_seek( $pop, 0 );
$links = array ();
while ($row = mysql_fetch_array($pop)){
$links[] = $row['username'];
}
However, a better / cleaner solution to your problem would be to put both values into their respective arrays during the first loop:
$links = array();
$images = array();
while ($row = mysql_fetch_assoc($pop)) {
$images[] = $row['image'];
$links[] = $row['username'];
}
Or, even cleaner - add an array to your array:
$avatars = array();
while ($row = mysql_fetch_assoc($pop)) {
array_push(
$avatars,
array('image' => $row['image'], 'username' => $row['username'])
);
}
var_dump($avatars);
First off, Please, don't use mysql_* functions in new code. They are no longer maintained and the deprecation process has begun on it. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
Try with mysql_data_seek($pop, 0) between the two while loops or replace your code with this:
$images = array();
$links = array();
while ($row = mysql_fetch_array($pop)) {
$images[] = $row['image'];
$links[] = $row['username'];
}
You've already iterated over the entire result set in the first block, you need to re-seek the pointer to the begining of the the result set between the two blocks of code by doing:
mysql_data_seek($pop, 0);
Wrong syntax.
while ($row = mysql_fetch_array($pop, MYSQL_ASSOC))

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