Get and echo mysql Array from query - mysql

I'm trying to get an array of id's from my database and then be able to echo out each id.
Something like this:
$query = mysql_query("SELECT id FROM TableName WHERE field = 'test' ORDER BY id DESC") or die(mysql_error());
$row = mysql_fetch_array($query);
echo "array: ".$row[1]." <br>";
echo "array: ".$row[2]." <br>";
echo "array: ".$row[3]." <br>";
This doesn't seem to be working though?

The problem is that mysql_fetch_array fetches an ARRAY, which is 0-based. You're fetching a single field from the database, which will be stored at $row[0] in your result array. Since you're echoing out only row[1] through row[3], you'll never see the result:
$row = mysql_fetch_array($query);
print_r($row);
should give you:
Array (
0 => 'id_field_value_here'
)
and
echo $row[0]
would also output
id_field_value_here

mysql_fetch_array fetches 1 row. You need to do something like
...
$res = array();
while ($row = mysql_fetch_array($query))
{
$res[] = $row;
}
//now $res[0] - 1st row, $res[1] - 2nd, etc

Related

PDO query returns multiple arrays. How to uniquely identify them?

This query returns 13 individual arrays:
$array = array($pgff_id, $pgfm_id, $pgmf_id, $pgmm_id, $mgff_id, $mgfm_id, $mgmf_id, $mgmm_id, $pgf_id, $pgm_id, $mgf_id, $mgm_id, $fid, $mid);
foreach($array as $id) {
$stmt = $db->prepare("SELECT birth_year, death_year FROM index WHERE id = ?");
$stmt->execute([$id]);
$data = $stmt->fetch(PDO::FETCH_ASSOC);
print_r shows that they look like this:
Array ([birth_year] => 1750 [death_year] => 1824)
Array ([birth_year] => 1770 [death_year] => 1836)
... etc
Is it possible to assign a number or name to these individual arrays? The results are not useful without a way to identify them.
I tried doing it like shown below. This way does number the arrays but orders the results as they are found in the table. I really need the results ordered as they are in $array (which the first method does manage).
$in = str_repeat('?,', count($array) - 1) . '?';
$sql = "SELECT birth_year, death_year FROM index WHERE id IN ($in)";
$stmt = $db->prepare($sql);
$stmt->execute($array);
$data = $stmt->fetchAll();
Taking your code and adding in id as an expression in the query would result in this:
$in = str_repeat('?,', count($array));
$sql = "SELECT id, birth_year, death_year FROM index WHERE id IN ($in)";
$stmt = $db->prepare($sql);
$stmt->execute($array);
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
echo "here starts another row:<br>";
echo "id = ".$row["id"]."<br>";
echo "birth_year = ".$row["birth_year"]."<br>";
echo "death_year = ".$row["death_year"]."<br>";
}
So, that's how you can access it.
You can rearrange the data in the rows after you've received them from the database, again by using a foreach loop:
$birth = [];
$death = [];
foreach ($rows as $row) {
$id = $row["id"];
$birth[$id] = $row["birth_year"];
$death[$id] = $row["death_year"];
}
Now you can access both arrays to get the birth or death year based on the id like this:
echo $birth[4]. 'and '. $death[4];
where id is 4.

MYSQL Query fail to select possible result

I want to get all emp_ids of employees which is manager_id equal to login user_id. But why this query show only first result of the column. I could not able to find the problem.
$userID=$_SESSION['userID'];
var_dump($userID);
$result1 = mysql_query("SELECT emp_id FROM employee where manager_id='$userID' ORDER BY emp_id");
$array = mysql_fetch_array($result1);
$id1=$array['emp_id'];
Please help !
You should loop over the result
and eg: you can store all the empID in an array
$cnt = 0;
while ($row = mysql_fetch_array($result1)) {
echo "ID: " . $row[0] ;
$myArrayOfEmpID[$cnt] = $row[0];
$cnt++;
}
instead you only set
$array = mysql_fetch_array($result1);
$id1=$array['emp_id'];

How to look for values in database and return an array of values

I'm looking for a way to search a MySQL database for specific values and put these in an array.
The contacts table has name,email,group,Phone...
I would like to search the database by group and return the email adresses in an array, separated by , (comma) to use further in my code.
What is the best way to do this?
$result = mysqli_query($link,"SELECT * FROM Contacts WHERE Group='Group 1'")
or die(mysqli_error());
...
while($row = mysqli_fetch_array( $result ))
{
array ( row->email,...)
}
Here you have different options beginning with:
Update your select query to only display the email, if you don't require the other fields this is the way to go
In your loop just add only the email field to the array
$dataArray[] = $row->email;
$result = mysqli_query($link,"SELECT email FROM Contacts WHERE Group='Group 1'")
or die(mysqli_error());
$emailArray = [];
while($row = mysqli_fetch_array( $result ))
{
array_push($emailArray,$row->email);
}
$responseEmail = implode(",", $emailArray);
Hope this will works!
I found the way of what I was trying to do. I needed a selectbox with values from the database.
....
$query = mysqli_query($link,"SELECT * FROM XXX WHERE category='$category' AND stelplaats='$stelplaats'");
echo '<td><select name ="collega" required>';
echo '<option value"">---</option>';
while ($row2 = mysqli_fetch_array( $query ))
{
echo '<option value =" '.$row2['id'].'"';
echo '>'.$row2['name'].'</option>';
}
echo '</select></td></tr>';
....

Data from 2 Tables in MySQL

I have a table ORDERS and a table MASTERBASE.
Now I would like to output everything from the table Orders
AND
the data that corresponds to the booknumber(s) for each order.
There can be several booknumbers for each ORDER
The code only returns 1 order with book details, but there are several orders ..
<?
require "../LAB MANU/DbConnect.php";
mysql_query('SET NAMES UTF8');
$raw_results = mysql_query("SELECT * FROM ORDERS WHERE id > 0");
$num_rows = mysql_num_rows($raw_results);
if(mysql_num_rows($raw_results) > 0){ // if one or more rows are returned do following
while($results = mysql_fetch_array($raw_results)){
echo $results ["id"];
echo "<br /><br />";
echo $results ["firstname"];
echo "<br /><br />";
echo $results ["name"];
echo "<br /><br />";
$ids = $results ["booknumbers"];
require "../LAB MANU/DbConnect.php";
mysql_query('SET NAMES UTF8');
$raw_results = mysql_query("SELECT * FROM MASTERBASE_VOLLEDIG WHERE BOEKNUMMER IN ({$ids})");
$num_rows = mysql_num_rows($raw_results);
if(mysql_num_rows($raw_results) > 0){ // if one or more rows are returned do following
while($results = mysql_fetch_array($raw_results)){
// $results = mysql_fetch_array($raw_results) puts data from database into array, while it's valid it does the loop
echo $results ["BESCHRIJVING"];
}}}}
?>
I Think you should change variable names
$raw_results to another one.Because this variable get a new value inside the loop.

Why does this query get all users?

so i have this query to determine whether or not it should count towards one entry in a table or not. however, it grabs all the users entries and disobays my
"dc.userid = ". $user ."
in an above query i use to gather what the user actually has inputted. and that works fine. however, when i exclude something it fetches all the entries from every user.
i will provide more code if noone can solve it from here. but i ive set $total above. in my case its 4. one entry should be excluded. but it fetches all entries which arent user = 1 and excludes them. in this case 11, which makes the $total variable -8 and not 3 as it should be. why is that?
$query3 = "SELECT IFNULL(dc.amount, 0) amount, dt.drop_id, dc.drop_id, dc.boss_id, dc.userid, dt.excl
FROM droptable dt
LEFT JOIN dropcounter dc
ON dt.boss_id = dc.boss_id AND dc.drop_id = dt.drop_id AND dc.userid = ". $user ."
WHERE dt.excl = 1 AND dc.userid = ". $user ."";
$stmt = $pdo->prepare($query3);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($result as $row){
$amount = $row['amount'];
echo $amount;
echo "<br>";
if (empty($amount)){}
else {
$total -= $amount;
}
}
echo $total;