I've got an array extracted from MySQL called "$agents", looking like:
Array (
[0] => Array ( [agent] => Agent/1002 [total] => 02:11:07 )
[1] => Array ( [agent] => Agent/1400 [total] => 01:49:53 )
[2] => Array ( [agent] => Agent/1500 [total] => 03:26:29 ) )
Then another MySQL query creates a table as:
while ($row = mysql_fetch_row($q)) {
$result .="<tr><td>".$row[0]."</td><td align=center>".
$row[1]."</td><td align=center>".
$row[2]."</td><td align=center>".
$row[3]."</td><td align=center>".$agents['0']['total']."</tr>";
}
How can I get the 'total' value from the array displayed in the last column of the table?
I want to insert the total for each agent. With an if statement, very simplified, like:
if $row[0] == $agents['0']['agent'] echo $agents['0']['total'] else echo 'NONE'"
Tried with "foreach" loop, but didn't get it to work.
Any ideas/suggestions of how this can be done?
You could initialize a counter above the second fetching. Like this:
$agents = holds your first data fetches from db
$i = 0; // initialize a counter
while ($row = mysql_fetch_row($q)) {
// condition block
if($row[0] == $agents[$i]['agent']) {
$total = $agents[$i]['total']; // if they match, assign the total
} else {
$total = ''; // else just assign an empty string
}
$result .="
<tr><td>".$row[0]."</td>
<td align=center>".$row[1]."</td>
<td align=center>".$row[2]."</td><td align=center>".$row[3]."</td>
<td align=center>".$total."</tr>
";
$i++; // increment
}
Related
I am working on online TV series website and can't figure out this one need to get values from array which is inside array.
This is structure contains $seasons variable:
Array
(
[0] => Array
(
[0] => link1-1
[1] => link1-2
[2] => link1-3
)
[1] => Array
(
[0] => link2-1
[1] => link2-2
[2] => link2-3
)
)
i need to get values like:
0
link1-1
link1-2
link1-3
1
link2-1
link2-2
link2-3
and then put them inside html video tag, but i can't figure out how to get values correctly
tried:
while ($row = $result->fetch_assoc()) {
$season_count = $row['season_count'];
$seasons = array_map("str_getcsv", explode("___", $row['en_url']));
array_shift($seasons);
for($i = 0; $i < count($seasons); $i++){
print_r($seasons[$i][*]); // i need equivalent of * to select all values of each array
}
break;
}
foreach ($seasons as $season){
foreach ($season as $link) {
echo '<video src="' . $link . '"><video>';
}
}
And next time - please formulate your task clearly.
Having issues with an array being parsed..
Here is a dump from the $_GET var
Array
(
[perm0] => Array
(
[0] => View
[1] => Add
[2] => Edit
[3] => Delete
[4] => Export
)
[perm1] => Array
(
[0] => View
[1] => Add
[2] => Export
)
[add] =>
)
When I try and use a foreach to insert into the db its only inserting the first item.
I am need to add the number based on the perm[] value such as perm0, perm1 etc
Here is my code
$i = 0;
$id = 0;
foreach($_GET['perm'.$i] as $permission)
{
do {
$perms = implode(":",$_GET['perm'.$i]);
mysqli_query($dbc,"INSERT INTO `permissions` (`mid`,`uid`,`permissions`) VALUES ('$id','99','$perms')");
echo mysqli_error($dbc);
} while(strpos($permission, $i) !== false);
$id++;
$i++;
}
I would have thought this would be really simple so I dont know why I'm having issues with it
The problem is that you are always only looking at the first item, your statement...
foreach($_GET['perm'.$i] as $permission)
will only ever pick up the perm0 item, even though you increment $i in the loop.
Instead, this code loops over all $_GET values, checks if they are the permN values and then inserts the value. I've also converted to prepared statements to add some level of security...
$i = 0;
$insert = mysqli_prepare ($dbc,"INSERT INTO
`permissions` (`mid`,`uid`,`permissions`)
VALUES (?,'99',?)");
foreach ( $_GET as $key => $param ) {
if ( $key == "perm$i" ) {
$perms = implode(":",$param);
mysqli_stmt_bind_param ($insert, "is", $i, $perms);
mysqli_execute($insert);
$i++;
}
}
As it's difficult for me to test this, please let me know if you have issues.
Array (
[modo_prep] =>
[modo_serv] =>
[id_prod_comp] => 18
[id_ingrediente] =>
Array (
[0] => 16
[1] => 17
[2] => 18
)
[qtd] => Array (
[0] => 10
[1] => 100
[2] => 1000
)
[rend_kg] => Array (
[0] => 20
[1] => 200
[2] => 2000
)
[submit] => Guardar
[id_receita] => 0
)
(post array) and need to be dynamic insert, so i want to do a universal post function to insert.
with simple array its ok 2 dimensoions there is a problem because i cannot match 1st value of N and so on, i need to be each array but same position each one sub-arrays to put in insert sentence.
so example: i have 1 row product, dinamic jquery (id_product[]) and i dont want to put the keys i want the script read all post data and put simple array in one table and the other N in other mysql table and each loop create 1 record with same key of each N sub arrays. row 1 has 3 fields it comes with 3 arrays, each row but if i put N i need to deal with that.
Code:
<?
ERROR_REPORTING(E_ERROR);
if($_POST['submit'] == TRUE){
$table = 'receitas';
$table2 = 'receitas_componentes';
$element1 = array();
$element3 = array();
$i=0;
foreach ($_POST as $key =>$valor){
if( $key != 'submit'){
if( !is_array($valor )){
$element1[$key] = $valor;
$colnames = "`".implode("`, `", array_keys($element1))."`";
$colvals = "'".implode("', '", $element1)."'";
$query_element1="INSERT INTO `".$table."` (".$colnames.") VALUES (".$colvals.")";
}else{
//echo $colvals = "'".implode("', '", $element1)."'";
$count = sizeof($valor);
extract_1_array($valor,0);
//else
}
//not submit
}
}
//echo $query_element1;
//mysql_query($query_element1);
$id_receita= mysql_insert_id();
//$_POST['id_receita']=$id_receita;
}
function extract_1_array($valor, $increment){
$i=0;
foreach ($valor as $key2 => $ingredientes){
$subarray[$i] .=$ingredientes ;
$i++;
}
echo $subarray[$i]; echo("<br>");
//$var10= implode($subarray[0]);
}
//echo $var10;
?>
<br><br><br><br><br><br><br><br>
blank
This question already has answers here:
get array of rows with mysqli result
(2 answers)
Closed 2 years ago.
please check out my code below. With that class I am able to display results like so:
$connectTest = new testResults();
$test = $connectTest->grabResults(test, id, id);
echo $test['id'];
echo $test['name'];
echo $test['address'];
In my database I have several fields in the "test" table. I go to my page using index.php?id=1. With this I am displaying just the results from one row because it grabs all results WHERE id = 1.
What I need is the class below to display multiple results. It just displays one row. But if I have multiple rows with id = 1 I would like to display these results, but I cannot get it to work. I have tried a lot of things but I always end up with just one result.
class:
class testResults
{
public function grabResults($table, $field, $id)
{
$result = $this->db->mysqli->query("SELECT * FROM $table WHERE $field = $id");
$resultData[] = array();
if(!$result)
{
return false;
}
while($row = $result->fetch_assoc())
{
$rows[] = $row;
}
foreach ($rows as $resultData)
{
return $resultData;
}
}
}
Edit:
Array ( [id] => 25 [name] => test [status] => 1 )
Array ( [id] => 25 [name] => test [status] => 3 )
Array ( [id] => 25 [name] => test [status] => 5 )
Array ( [id] => 25 [name] => test [status] => 4 )
Array ( [id] => 26 [name] => test [status] => 1 )
Array ( [id] => 26 [name] => test [status] => 3 )
Array ( [id] => 27 [name] => test [status] => 1 )
Array ( [id] => 27 [name] => test [status] => 3 )
Array ( [id] => 27 [name] => test [status] => 5 )
Array ( [id] => 27 [name] => test [status] => 4 )
Array ( [id] => 27 [name] => test [status] => 2 )
Array ( [id] => 27 [name] => test [status] => 4 )
Array ( [id] => 27 [name] => test [status] => 1 )
I am getting results as above, any way to easily display these results in an echo? For each id there are different results, so results will vary with each query. So I would like to display results in a table for example like so:
echo '<table>
<tr>
<td>$id</td>
<td>$name</td>
<td>$status</td>
</tr>
</table>';
So all results will be displayed like in a while loop.
You can just return the array from function and then loop in your script
while($row = $result->fetch_assoc())
{
$rows[] = $row;
}
return $rows;
The you can loop in your script
$test = $connectTest->grabResults(test, id, id);
foreach($test as $value)
{
print_r($value);
}
Upon OP edit
If you need to print them separate you can access all elements with variable name and scopes with keys as follow
$test = $connectTest->grabResults(test, id, id);
echo '<table>';
foreach($test as $value)
{
echo '<tr>
<td>'.$value['id'].'</td>
<td>'.$value['name'].'</td>
<td>'.$value['status'].'</td>
</tr>';
}
echo '</table>';
Since you are passing the full resultset to another layer for processing, you can skip the loop to generate an array of associative arrays from the resultset.
class testResults {
public function grabResults($table, $field, $id) {
// For the record, I feel a prepared statement is in order here...
$result = $this->db->mysqli->query("SELECT * FROM $table WHERE $field = $id");
return $result->fetch_all(MYSQLI_ASSOC); // just in case you wanted to see the column names
}
}
Then when you want to generate an html table from the returned array of associative arrays, use implode() as a flexible solution that doesn't care if you ever change the number of columns being passed in -- it will handle an indefinite number of columns.
if ($resultset = grabResults("tests", "name", "test")) {
echo "<table>";
foreach ($resultset as $i => $row) {
// if (!$i) { echo "<tr><th>" , implode("</th><th>", array_keys($row)) , "</th></tr>"; }
echo "<tr><td>" , implode("</td><td>", $row) , "</td><tr>"
}
echo "</table>";
}
It looks like you are returning a single row of your results with this bit of the function:
foreach ($rows as $resultData)
{
return $resultData;
}
You should just return the whole thing instead.
while($row = $result->fetch_assoc())
{
$rows[] = $row;
}
return $rows;
return inside foreach() iteration means stop right after first iteration. Therefore you will be always getting only the first result.
You'd better write this as:
public function grabResults($table, $field, $id)
{
$result = $this->db->mysqli->query("SELECT * FROM $table WHERE $field = $id");
$rows = array();
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
I am trying to fetch records from MySql and display them in an array along with column headers using PDO, reason I am doing this is because i want to export them in an excel and I am using php-excel
right now the following code displays the records perfectly fine in an array and I am able to export them just fine
while ($row[] = $stmt->fetch(PDO::FETCH_ASSOC)) :
$data = $row;
endwhile;
The array i get as a result of above code is as following
Array
(
[0] => Array
(
[user_id] => 1
[fname] => First Name
[lname] => Last Name
)
[1] => Array
(
[user_id] => 91
[fname] => First Name
[lname] => Last Name
)
)
But the problem is I am missing column headers in excel, so for that I need to display the MySql column headers in an array as well.
I am using the following code to create an array for column headers
for ($i = 0; $i < $stmt->columnCount(); $i++) {
$col = $stmt->getColumnMeta($i);
$columns[] = $col['name'];
}
but this gives me an array in following format
Array
(
[0] => user_id
[1] => fname
[2] => lname
)
whereas I need the column header array in following format
Array
(
[0] => Array
(
[user_id] => user_id
[fname] => fname
[lname] => lname
)
)
I will appreciate any help.
I assume you want the headers to be in the same array. In that case you would do this before the while loop
$data[0] = array();
for ($i = 0; $i < $stmt->columnCount(); $i++) {
$col = $stmt->getColumnMeta($i);
$data[0][$col['name']] = $col['name'];
}
Also, the while loop is a little inefficient. You're pushing each row into the $row array and then copying it into $data every single time. It should be done like this instead:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) :
$data[] = $row;
endwhile;
This should get you:
$data = Array
(
[0] => Array
(
[user_id] => user_id
[fname] => fname
[lname] => lname
)
[1] => Array
(
[user_id] => value...
...
)
...
)
Instead of letting it auto-number, just provide the name again as the key:
for ($i = 0; $i < $stmt->columnCount(); $i++) {
$col = $stmt->getColumnMeta($i);
$columns[$col['name']] = $col['name'];
}
Example: https://eval.in/117424
Might be easier:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
if(!isset($data)) {
$data[] = array_combine(array_keys($row), array_keys($row));
}
$data[] = $row;
}
Or you could add them after the fact using array_unshift().
Or in a separate array:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
if(!isset($col)) {
$col[] = array_combine(array_keys($row), array_keys($row));
}
$data[] = $row;
}