jmansa
January 21, 2011, 6:27pm
1
I’m trying to get this array:
$names = array(
"Peter Hansen"=>"245",
"Chad Larsson"=>"145",
"Tim Laural"
);
Out of an sql query but with no luck?!? This is what I have done:
$sql = "SELECT * FROM users";
$result = mysql_query($sql) or die("Error: (" . mysql_errno() . ") " . mysql_error());
$names= array();
while($row = mysql_fetch_array($result)){
$names[] = "".$row['fname']." ".$row['lname']."=>".$row['new_userid']."";
}
How do I achive this?
Thanks in advance
rpkamp
January 21, 2011, 6:42pm
2
That last bit should be:
while($row = mysql_fetch_array($result)){
$names[ $row['fname'].' '.$row['lname'] ] = $row['new_userid'];
}
jmansa, just a little note to ad on here, if your concatenating first and last names stored in a database table, you can have MySQL do the concatenating instead on having php do it:
<?php
$names=array();
$sql="
SELECT
id_field
, CONCAT(fname,' ',lname) AS full_name
FROM
users
";
$result = mysql_query($sql) or die("Error: (" . mysql_errno() . ") " . mysql_error());
while($row = mysql_fetch_array($result)) {
$names[] = $row;
}
?>
The field name in the query "id_field would need to be replaced with whatever the name is of the id field.