Forum Moderators: coopster

Message Too Old, No Replies

string index

         

wannabem

5:51 pm on Apr 14, 2010 (gmt 0)

10+ Year Member



I have a question ..

I wonder how i can echo string index N from a list...

let me clarify;

1 john | john@mail.com
2 mary | mary@mail.com
3 uncle | uncle@mail.com

$users = $db->get_results("SELECT name, email FROM users");

Now $users contains the results..

If i only want to echo mary .. how can i do that?

echo $users[2];

the above will not do the trick. I need this because i want to select the last 4 rows in my database and echo them on different areas on the screen.

thanks in advance! :-)

rocknbil

7:16 pm on Apr 14, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



There's a number of ways. Starting with this, which is the root of your question,

need this because i want to select the last 4 rows in my database


First, get your select out of the command and into a variable. :-) This will make it much easier to experiment with and debug.

Second, you say "last four" but what's last four? Assuming your first column is auto-increment, it should be fairly reliable to use order by the auto increment column, and limit 4 to get the last four, but there are a couple conditions by which it many not actually be the last four (sorry, I forget what those conditions are . . . . ) It may be to your advantage to add a datetime field and order by that field instead, as that field will have other important uses (like, who signed up today . . . )

Assuming the first column is named "id" (as is too often the case, to the advantage of hackers,)

$how_many=4;
$direction='desc';

$query = "select name, email from users order by id $direction limit $how_many";

$users = $db->get_results($query);

... should do the trick. I put the direction and number of rows in variables because this is how you will probably eventually need them - as in, selectable from a search form. Even if not, at the top of the script in an easy to locate config section.

A little more info on this, so you know what's happening:

Now $users contains the results.


Not exactly. :-) What you need to do is command one of the row functions, mysql_fetch_assoc or mysql fetch_array, and judging by your code, it looks like you are using a connection class I've seen. So an easier approach might be something like this:


$how_many=4;
$direction='desc';
//
$query = "select name, email from users order by id $direction limit $how_many";
//
$result = $db->query($query);
while ($row=$db->fetch_array($result)) {
// you can use ASSOCIATIVE or INDEXED
// queries here. Displaying both.
echo "<p>Associative: " . $row['name'] . " " . $row['email'] . "</p>\n";
echo "<p>Indexed: " . $row[0] . " " . $row[1] . "</p>\n";
}


If you had done select *, 0 (zero) would be id, 1 would be name, 2 would be email.

wannabem

7:48 pm on Apr 14, 2010 (gmt 0)

10+ Year Member



Thank you for being so elaborate.

I am a newbie with php and mysql.
But looking at your code, you access the datase a first time to get some results, and then again in a loop. isn't this a heavy load on the mysql server, if there are 1000 users accessing at the same time?

and sorry to ask again, but isnt there a more elegant way of doing this?

many years ago in basic you could do;

A$[1] = "John"
A$[2] = "Mary"
A$[3] = "smith"

Print A$[2] .. this would print Mary on the screen.

From your example, is it not possible to print the second row with something like this;

echo $query->name[2];

CyBerAliEn

8:31 pm on Apr 14, 2010 (gmt 0)

10+ Year Member



Some understandings...

A query is just the SENTENCE that tells the database what to do; it is a command. Such as: "SELECT * FROM users". You store this query statement as a variable, because it allows better manipulation, debugging, etc on your part.

The way PHP works (generally), is that you write a query statement ($query) and then pass it to query function/method, which takes this statement from PHP and pipes it into mySQL. A la:
$db->query($query)

This returns a "resource ID" that is internal to PHP, which is stored in $result. Basically, PHP took your query statement, sent it over to mySQL and let mySQL run the statement. mySQL then has output and sends it back to PHP. PHP holds onto this output internally, and "references" it via a resource ID. To get the mySQL output, you have to use PHP functions/methods that tell PHP to interact with the resource and to return something that you want. In this case, you are doing this through a WHILE loop:
$row=$db->fetch_array($result)

What does this do? It takes your 'resource ID' for this specific query ($result IS/contains value of the resource ID)... passes it to 'fetch_array'. This method takes your resource ID, and hence your mySQL output, and then returns an ARRAY of the first row of the output. Hence, this output is assigned to 'row'. Each time you call this, PHP will increment to the next row of the output; so next time you loop, you get the next row of the output. When no more output is left, it "errors" (a boolean false output I believe), which makes the WHILE loop stop.

So PHP takes your first row, and turns it into an ARRAY for you to access. Using the above code (rocknbil), you can then access your query's mySQL output via a PHP array where "columns" are stored by both numeric and associative array keys. (my preference is associative)

So basically... your mySQL output becomes available to PHP. You loop through the results, and with each result you can display the output row (or whatever you need).

So if your table has schema~: ID,name,username,password
And you are looping through the results (and all of these columns are selected in your query statement), then you can access the row's value of "name" via either:
$name = $row['name'];
$name = $row[1];

You cannot do "$query->name[2]" because 'query' is a string, not an object. And 'name' is not a method. And methods do not have '[2]' notation. The '[2]' notation is used on arrays to indicate which array key you want to access of the array. IE: '$row' is an array, so if you want to access the item with key 'name', you do "$row['name']". Etc.

Let's say you have a PHP array...
$fruits = array('banana','orange','grape','strawberry');

If you "display" this array (via function print_r() or such), you get ~:
Array (
0 => banana
1 => orange
2 => grape
3 => strawberry
)

So, if you want to get 'orange', and you know its key is "1", you simply do:
echo $fruits[1];


Hope this helps!

CyBerAliEn

8:34 pm on Apr 14, 2010 (gmt 0)

10+ Year Member



Shoot... my first purpose was to comment this:
But looking at your code, you access the datase a first time to get some results, and then again in a loop. isn't this a heavy load on the mysql server, if there are 1000 users accessing at the same time?


rocknbil's code only runs the query to mySQL ONCE! This is done when "result" is set via: $db->query($query)

Once that is done, PHP stores the output from mySQL and the query is NOT run again (unless you explicitly tell it to).

So mySQL only sees one load. Following this, the "output" is looped through all via PHP. So if you had 1000 users and were querying out ALL of them... the query would run ONCE... and then you'd have PHP loop 1000 times... each time, PHP will grab out the row from the output internally. But this is not a load to the database server.

wannabem

6:32 am on Apr 15, 2010 (gmt 0)

10+ Year Member



you helped me a lot! thanks man