PHP code to be checked - php

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))

Related

looping through xpath results

I have gone to the db and created an array of url's.
Then I go through the array and use xpath to tell me how many links there are per url.
This is where my head hurts.
I have a count for each url of the no of objects in each url. So I'm now trying to collect each of the nodevalues from part 2.
I'm obviously doing something wrong but need some guidence please
$items = array();
$query = "SELECT * FROM `urls`";
if( $result = mysqli_query($sql,$query));
{
// Return the number of rows in result set
$rowcount=mysqli_num_rows($result);
while ($row = $result->fetch_assoc()) {
$items[] = $row;
}
}
echo '<pre>';
print_r($items);
// $product = array();
echo $rowcount;
for ($x=0; $x<$rowcount; $x++){
$scrapeurl[$x] = $items[$x][url];
echo $scrapeurl[$x];
$xpath[$x] = new XPATH($scrapeurl[$x]);
$urls[$x] = $xpath[$x]->query("//div[#class='infodata']/strong/a[contains(#id,'test_title')]/#href");
$count[$x] = $urls[$x]->length;
$data = array();
for ($i=0; $i<$count[$x]; $i++){
$data[$i]['url'] = $urls[$x]->item($i)->nodeValue;
$data[] = $data[$i]['url'];
}
echo '<pre>';
print_r($data);
A bit late apologies but resolved the issue. Maybe too tired but came down to a couple of issues.
Don't always believe what the browser renders in the HTML. Look at the source! I found that tbody as an example is filled into HTML by Firefox at least in reality the source was different so I was never going to hit the right node.
looping within loops - to remember when in a loop sometimes you have to loop again to drill down to the right result......
$data = array();
foreach($urls as $node){
foreach($node->childNodes as $child) {
$data[] = array($child->nodeName => $child->nodeValue);
}
}
$data = new RecursiveIteratorIterator(new RecursiveArrayIterator($data));
$data = iterator_to_array($data,false);

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.

Handling PHP array of unknown size

I have the following code that should select all the users in the relevant table in my database:
$hof = mysql_query("SELECT * FROM users");
$name = array();
$website = array();
$i=0;
while($result = mysql_fetch_array($hof)){
$name[$i] = $result['company'];
$website[$i] = $result['website'];
}
$i++;
I want to echo out the names and websites of all in the html section of my script (below the php) which will be a Hall of Frame of sorts. How would i do is? The fact that i do not know the size of the array deters me.
Usually, if i knew the size, i would so something like:
<?php echo $name[1];?>
<?php echo $name[2];?>
//and so on
Many thanks in advance. P.S. I plan to move across to MySQLi when i have the functionality of the website sorted first on localhost. Cheers
Your $i++; statement should be inside while loop
while($result = mysql_fetch_array($hof)){
$name[$i] = $result['company'];
$website[$i] = $result['website'];
$i++;
}
Better You do it like this,
$rows = array();
while($result = mysql_fetch_assoc($hof)){
$rows[] = $result;
}
and you echo them like this,
<?php
$len = count($name);
for($i=0;$i<$len;$i++){
echo $name[1];
}
?>
And for the alternative method use this,
<?php
foreach($rows as $row){
echo $row['name']; // use $row['website'] to echo website.
}
?>
foreach($name as $key=>$value){
echo $name[$key];
echo $website[$key];
}
Also there no need to take $i++, you can use following way
while($result = mysql_fetch_array($hof)){
$name[] = $result['company'];
$website[] = $result['website'];
}
See array in manual
First off the $i++ should be inside the loop.
To output them all, you could use implode(), or maybe foreach.
First, take your data into array
$data = array();
$sql = "SELECT * FROM users";
$res = mysql_query($sql) or trigger_error(mysql_error()."[$sql]");
while($row = mysql_fetch_array($res)){
$data[] = $row;
}
then use it anywhere you wish, say, in the template:
<ul>
<? foreach($data as $row): ?>
<li><?=$row['company']?></li>
<? endforeach ?>
</ul>
How about:
foreach ($name as $val)
{
echo $val;
}
you can use mysql_num_rows() to know the number of results returned by your query
$arrarySize = mysql_num_rows($hof);

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

format mysql data in array

I am pulling data from my database and trying to encode into JSON data using json_encode. But to make it easier to read in my android app. I was hopping to format it differently then I am currently doing. Please see bottom encode string example. Any help would be great. Thanks in Advance.
$result = $db->query($query);
while($info = mysql_fetch_array($result))
{
$content[] = $info;
}
$count = count($content);
$result=array();
for($i=0;$i<$count;$i++)
{
$result[id][] = $content[$i]['imageID'];
$result[name][] = $content[$i]['Name'];
$result[thumb][] = $content[$i]['Thumb'];
$result[path][] = $content[$i]['Path'];
}
echo json_encode($result);
{"id":["1","2","3"],"name":["Dragon","fly","bug"],"thumb":["thm_polaroid.jpg","thm_default.jpg","thm_enhanced-buzz-9667-1270841394-4.jpg"],"path":["polaroid.jpg","default.jpg","enhanced-buzz-9667-1270841394-4.jpg"]}
But I am trying to format my array like so when it is encoded by json_encode.
[{"id":"1","name":"Dragon","thumb":"thm_polaroid.jpg","path":"polaroid.jpg"},{"id":"2","name":"Fly","thumb":"thm_default.jpg","path":"default.jpg"},{"id":"3","name":"Bug","thumb":"thm_enhanced-buzz-9667-1270841394-4.jpg","path":"enhanced-buzz-9667-1270841394-4.jpg"}]
Well, there is a problem. This is not valid JSON:
{"image":["1","Dragon","thm_polaroid.jpg","polaroid.jpg"],
"image":["2","fly","thm_default.jpg","default.jpg"]}
A JSON object can only have one value per unique key. This means that your latter image key would clobber the value of the former.
If you are content with this, however:
[["1","Dragon","thm_polaroid.jpg","polaroid.jpg"],
["2","fly","thm_default.jpg","default.jpg"]]
Then you can simply use mysql_fetch_row:
$result = $db->query($query);
while($info = mysql_fetch_row($result))
{
$content[] = $info;
}
echo json_encode($content);
Side Note:
Generally, in PHP, it is best to use foreach( $arr as $val ) (or $arr as $key => $val). for loops should be limited to when they are strictly necessary.
You need to add the iterator $i to the setting array
for($i=0;$i<$count;$i++)
{
$result[$i][id] = $content[$i]['imageID'];
$result[$i][name] = $content[$i]['Name'];
$result[$i][thumb] = $content[$i]['Thumb'];
$result[$i][path] = $content[$i]['Path'];
}
<?
$result = $db->query($query);
while($info = mysql_fetch_array($result))
$content[] = $info;
$result=array();
$count = count($content);
for ($x=0;$x<$count;++$x)
{
$result[$x][] = $content[$x]['imageID'];
$result[$x][] = $content[$x]['Name'];
$result[$x][] = $content[$x]['Thumb'];
$result[$x][] = $content[$x]['Path'];
}
echo json_encode($result);
?>

Categories