Reputation: 35
i've got a db table which gets filled by a submit form.
the table consists of ID, usr_ID, name, and a lot more. i'm in the middle of making a custom table list in wordpress, and well.. i'm not the best at foreach.
how would i go about looping thru and only display each name and usr_id once when
example:
row 1:
id = 1, usr_id = 5, name = Alexander
row 2;
id = 2, usr_id = 4, name = james
row 3;
id = 3, usr_id = 5, name = Alexander
row 4
id = 4, usr_id = 4, name = james
how would i make a foreach statement that would print out:
usr_id = 5, name = Alexander
usr_id = 4, name = james
the purpose for the is to make each name clickable and then make a foreach statement only for the specific usr_id clicked on to see what has been submitted by each individual user
Upvotes: 0
Views: 683
Reputation: 1681
how would i make a foreach statement that would print out:
you can use this for array output:
foreach ($query as $v) {
echo "usr_id = ".$v['usr_id']." , name = ".$v['name'];
}
you can do this too for an array output :
foreach ($query as $key => $list){
echo $list['someindex'];
}
But I don't know if you want like that...
For complete documentation about foreach
, please read this... :)
Upvotes: 2
Reputation: 733
just to simplify things use
$name_arr=array();
foreach ($query as $v)
{
if(in_array($v['name'],$name_arr)==false)
{
$name_arr[]=$v['name'];
echo "usr_id = ".$v['usr_id']." , name = ".$v['name'];
}
}
this way each name comes only one
Upvotes: 0
Reputation: 1263
$dbhost = 'localhost'; $dbuser = 'DB USER'; $dbpass = 'DB USER PASSWORD'; $dbname = 'DB NAME';
$db = new PDO('mysql:host='.$dbhost.'; dbname='.$dbname, $dbuser, $dbpass, array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ));
foreach($db->query('SELECT id, usr_id, name FROM THE-TABLE WHERE id>=1') as $row) {
$id = $row['id'];
$usr_id = $row['usr_id'];
$name = $row['name'];
// DO WHATEVER HERE
}
or you indicated that the table had numerous columns... use a wild card
$dbhost = 'localhost'; $dbuser = 'DB USER'; $dbpass = 'DB USER PASSWORD'; $dbname = 'DB NAME';
$db = new PDO('mysql:host='.$dbhost.'; dbname='.$dbname, $dbuser, $dbpass, array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ));
foreach($db->query('SELECT * FROM THE-TABLE WHERE id>=1') as $row) {
$id = $row['id'];
$usr_id = $row['usr_id'];
$name = $row['name'];
# the rest of the columns
// DO WHATEVER HERE
}
Upvotes: 0
Reputation: 8033
Supposing you have $array
contains your data. If $array
is an associative array:
foreach($array as $a)
{
echo "usr_id = " . $a['usr_id'] . "- name = ". $a['name'];
}
And if $array
is an indexed array:
foreach($array as $a)
{
echo "usr_id = " . $a[1] . "- name = ".$a[2];
}
Upvotes: 0