Populate an Array with Results from mySql Query - php

I am having a problem with creating an array from the values received from a mySql query. I have the following code but I can't populate the array with the returned values. I assume that there is a problem with the while statement. Can anybody help me out?
$return_arr = array();
$searchTerm=$_GET['searchTerm'];
$query = "SELECT Actor.FirstName, Actor.LastName FROM Actors WHERE Actor.ActorFirstName LIKE '%$searchTerm%' ";
$stmt = $db->prepare($query);
$stmt->execute();
$stmt->store_result();
$numrows = $stmt->num_rows;
$stmt->bind_result($firstName, $lastName);
while($row = mysql_fetch_assoc($stmt) {
$return_arr[] = $row['FirstName'];
}

change your while loop
while($stmt->fetch())
{
$return_arr[] = $firstName;
}

Related

Replace value in array with result of mysqli_query

I'm having some trouble with php coding. What I want to do is following:
Create an array ($rows) and fil it with the results of a mysqli_query ($query1) --> OK
for each element in that array, replace the value of a certain key (pilot_rule_id) with the result of another mysqli_query ($query2). (the second query will return one row, since the id of the pilot table is the primary key).
So far I have
$id = "96707ac6-ecae-11ea-878d-005056bbb446";
$rows = array();
$query1 = mysqli_query($con, "SELECT * FROM pilot_time_schedule WHERE pilot_id='$id'");
while($r = mysqli_fetch_assoc($query1)) {
$rows[] = $r;
}
foreach($rows as $pilotRuleId) {
$pilotRuleId->$pilot_rule_id;
$query2 = mysqli_query($con, "SELECT name FROM pilot_rule WHERE id='$piloteRuleId'");
while($r = mysqli_fetch_assoc($query2)) {
$result[] = $r;
}
// Don't know how to continue from here
You can something like this:
$id = "96707ac6-ecae-11ea-878d-005056bbb446";
$stmt = $con->prepare('SELECT * FROM pilot_time_schedule WHERE pilot_id=?');
$stmt->bind_param('s', $id);
$stmt->execute();
$rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
foreach ($rows as $row) {
$stmt = $con->prepare('SELECT name FROM pilot_rule WHERE id=?');
$stmt->bind_param('s', $row['pilot_rule_id']);
$stmt->execute();
// replace with the `name` returned from the above statement.
$row['pilot_rule_id'] = $stmt->get_result()->fetch_row()[0] ?? null;
}
However, you really should learn about SQL joins instead. Using SQL joins you can avoid N+1 queries to the database.
$id = "96707ac6-ecae-11ea-878d-005056bbb446";
$stmt = $con->prepare('SELECT pilot_time_schedule.*, pilot_rule.name
FROM pilot_time_schedule
JOIN pilot_rule ON pilot_rule.id=pilot_time_schedule.pilot_rule_id
WHERE pilot_id=?');
$stmt->bind_param('s', $id);
$stmt->execute();
$rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
foreach ($rows as $row) {
echo $row['name']; // contains the name from pilot_rule
}

PHP PDO Output results outside while {}

Is it possible to output all database results outside of while loop?
I want to use it inside another echo.
$sql = $db->prepare("SELECT color FROM table WHERE type = :key");
$sql->bindValue(':key', $type, PDO::PARAM_STR);
$sql->execute();
while($rows = $sql->fetch(PDO::FETCH_BOTH)) {
$colors = $rows ['color'];
echo $colors; //Outputs all results
}
echo $colors; //Outputs only last result
Sure just store them to an array:
$sql = $db->prepare("SELECT color FROM table WHERE type = :key");
$sql->bindValue(':key', $type, PDO::PARAM_STR);
$sql->execute();
$colors = [];
while($rows = $sql->fetch(PDO::FETCH_BOTH)) {
$colors[] = $rows ['color'];
}
print_r($colors)
Instead of doing the while loop to save to an array you can just get all the results at once as an array with the PDOStatement::fetchAll method
$sql = $db->prepare("SELECT color FROM table WHERE type = :key");
$sql->bindValue(':key', $type, PDO::PARAM_STR);
$sql->execute();
$colors = $sql->fetchAll(PDO::FETCH_BOTH));
print_r($colors);

How to get number of results from a mysqli query?

So I'm doing this query:
'SELECT * FROM Album WHERE id = ?;'
using a prepare sql statement, and I was wondering how to get the number of results this query returns? B/c since every album id is unique this query should only return 1 album and I want to make sure that its doing that.
Code
$stmt = $mysqli->prepare('SELECT * FROM Album WHERE id = ?;');
$id = 2;
$stmt->bind_param('i', $id);
$executed = $stmt->execute();
$result = $stmt->get_result();
if($row = $result->fetch_assoc()){
$info['id'] = $row['id'];
$info['title'] = $row['title'];
$info['date_created'] = $row['date_created'];
$info['creator'] = $row['creator'];
}
// Send back the array as json
echo json_encode($info);
You can get it using $result->num_rows:
if ($row = $result->fetch_assoc()) {
$info['id'] = $row['id'];
$info['title'] = $row['title'];
$info['date_created'] = $row['date_created'];
$info['creator'] = $row['creator'];
/* determine number of rows result set */
$row_cnt = $result->num_rows;
printf("Result set has %d rows.\n", $row_cnt);
}
You can find more details on PHP Documentation.
I want to make sure that its doing that
In your code you are already doing that. The following condition
if($row = $result->fetch_assoc()){
does exactly what you want.
Just use COUNT(*)
SELECT COUNT(*) FROM Album WHERE id = ?;
Reference:
https://dev.mysql.com/doc/refman/5.7/en/counting-rows.html
Another way
$query = $dbh->prepare("SELECT * FROM Album WHERE id = ?");
$query->execute();
$count =$query->rowCount();
echo $count;

$stmt->fetch() not enter in while

I have write simple code in PHP, I'm a beginner in this language.
This is my code:
$id = "prova";
$query = "SELECT DISTINCT id_item FROM Users WHERE id = ? LIMIT 1 ";
if ($stmt = $conn->prepare($query))
{
$stmt->bind_param("s", $id);
$stmt->execute();
$stmt->bind_result($result);
while ($stmt->fetch()) {
$id_item = (int) $result;
}
}
My problem is that the cycle while is never executed, but I don't understand why.
Thanks in advance.

Fetching data from database into array

I am using mysqli to fetch data from the database and put it into an array with a while loop. When i echo out the array i get an empty array however in a function i previously did this code worked but it had a different result from the database. I know that the database is giving out good data because when i echo out the result $idGroup it gives me 2 which is correct.
Ps i know it will keep replacing itself because i don't specify an index
private function Groups()
{
$functionRun = 0;
$i = 0;
$helperArray = array();
$this->grouplist = array();
$query = "SELECT GroupName, Groups.idGroup
FROM Groups
INNER JOIN Members
ON Groups.idGroup = Members.idGroup
WHERE Members.idMember = ? ";
//prepare query and execute
if($stmt = $this->connection->prepare($query))
{
$stmt->bind_param('s', $this->id);
$stmt->execute();
$stmt->bind_result($GroupName, $idGroup);
while ($stmt->fetch())
{
$helperArray[] = $idGroup;
}
echo $helperArray;
}
Use print_r when dealing with arrays. Use echo on strings.
Try this
$query = "SELECT GroupName, Groups.idGroup
FROM Groups
INNER JOIN Members
ON Groups.idGroup = Members.idGroup
WHERE Members.idMember = ? ";
//prepare query and execute
if($stmt = $this->connection->prepare($query))
{
$stmt->bind_param('s', $this->id);
$stmt->execute();
$stmt->bind_result($GroupName, $idGroup);
$helperArray =array();
while ($stmt->fetch())
{
$helperArray[] = $idGroup;
}
print_r($helperArray);
}

Categories