Foreach for database - php

So I have the following code:
<?php
$post_id = 1;
$name_result = $wpdb->get_results("SELECT * FROM rh_names WHERE post_id = '$post_id' ");
?>
<?php if (!empty($name_result)) { ?>
<?php foreach ($name_result as $names) {?>
<div class="names">
<script type="text/javascript">
var nameXML = <?php echo json_encode($names); ?>;
document.write(nameXML.last_name);
</script>
</div>
<?php } ?>
<?php } ?>
In the database, I have two results that should show up, but I am only getting one.
Why am I only getting one result when two should show up? What am I missing?
Thanks!

document.write will replace all document element so you can see last result only try
document.getElementById('results').innerHTML = res_content;

Related

Display mysqli result multiple times [duplicate]

This question already has answers here:
How can I use mysqli_fetch_array() twice?
(4 answers)
Closed 3 months ago.
I asked this recently but it got marked as duplicate and deleted.
Please look at my question before marking it down because it is not the same and I am struggling to figure this out.
I want to echo the 'company' and 'area' results from a MYSQLI query into my page, at separate points in the body of a php page.
Only the first echo will show. Please show my mistake.
<?php
$path = $_SERVER['DOCUMENT_ROOT'];
$path .= "/Connections/****";
include_once($path);
$dbhandle=mysqli_connect($hostname_Demo, $username_Demo, $password_Demo, $database_Demo);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql_RS1="SELECT * from CompanyName where area = 1";
$result=mysqli_query($dbhandle,$sql_RS1);
?>
<head>
<title>TEST</title>
</head>
<body>
<?php
while($row = mysqli_fetch_assoc($result))
{
echo $row['company'];
}
?>
<?php
while($row = mysqli_fetch_assoc($result))
{
echo $row['area'];
}
?>
<?php $dbhandle->close(); ?>
</body>
</html>
You can use this code
<?php
while($row = mysqli_fetch_assoc($result))
{
$data_array[] = $row;
}
foreach ($data_array as $data) {
echo $data['company'];
}
foreach ($data_array as $data) {
echo $data['area'];
}
Do like this with.., You don't want to have to make more queries to your database.
You are fetching same row two different which is not correct.
Something like this should work
<?php
$path = $_SERVER['DOCUMENT_ROOT'];
$path .= "/Connections/****";
include_once($path);
$dbhandle=mysqli_connect($hostname_Demo, $username_Demo, $password_Demo, $database_Demo);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql_RS1="SELECT * from CompanyName where area = 1";
$result=mysqli_query($dbhandle,$sql_RS1);
$row =array();
while ($x= mysqli_fetch_assoc($result))
$row[]=$x;
$i=0;
?>
<head>
<title>TEST</title>
</head>
<body>
<?php
echo $row[i]['company'];
?>
<?php
echo $row[i]['area'];
$i++;
?>
try merging them it looks like they are just the same
<?php
while($row = mysqli_fetch_assoc($result))
{
echo $row['company']."
".$row['area'];
}
?>
This is what I ended with. It works so I hope it is correct. Thanks for everyones help.
$sql_RS1="SELECT * from CompanyName where area = 1";
$result=mysqli_query($dbhandle,$sql_RS1);
$row =array();
while ($x= mysqli_fetch_assoc($result))
$row_RS1=$x;
?>
<?php
$sql_RS2="SELECT * from employees where EmployeeID = 79";
$result=mysqli_query($dbhandle,$sql_RS2);
$row_RS2 =array();
while ($x= mysqli_fetch_assoc($result))
$row_RS2=$x;
?>
<head>
<title>TEST</title>
</head>
<body>
<p>
<?php echo $row_RS1['company']; ?>
</p>
<p>
<?php echo $row_RS1['company']; ?>
</p>
<p>
<?php echo $row_RS1['area']; ?>
</p>
<p>
<?php echo $row_RS2['EmployeeID']; ?>
</p>
<p>
<?php echo $row_RS2['Surname']; ?>
</p>
<p>
<?php echo $row_RS2['EmployeeID']; ?>
</p>
<p>
<?php $dbhandle->close(); ?>
</p>
</body>

For each inside other for each on view MVC PHP

I'm trying to give structure to my code and i am facing a problem.
I'm looping through a sql query response and for each element i'm trying to retrieve other related elements. It works in my controller without problem but when i'm trying to repeat in the view I always get the same value for the related element
My controller:
<?php
include_once('class/guide.class.php');
$bdd = new DBHandler();
$req = guide::getGuides($bdd,0,5);
foreach ($req as $results => $poi)
{
$req[$results]['id'] = htmlspecialchars($poi['id']);;
$req[$results]['name'] = nl2br(htmlspecialchars($poi['name']));
$guide = new guide($results['name'],$bdd);
$guidePois = $guide->getGuidePois($poi['id']);
foreach ($guidePois as $res => $re)
{
echo $guidePois[$res]['id'];
echo $guidePois[$res]['name'];
$guidePois[$res]['id'] = htmlspecialchars($re['id']);
$guidePois[$res]['name'] = nl2br(htmlspecialchars($re['name']));
}
}
include_once('listing.php');
here, you see that I echo the ids/names of the related list of element and it works well, the output is correct for each element of the first list.
When i do it in my view:
<?php
foreach($req as $poi)
{
?>
<div class="news">
<h3>
<?php echo $poi['id']; ?>
<em>: <?php echo $poi['name']; ?></em>
</h3>
<?php foreach($guidePois as $re)
{
?>
<h4>
<?php echo $re['id']; ?>:
<?php echo $re['name']; ?>
</h4>
<?php
}
?>
</div>
<?php
}
?>
Somehow the first list output are the good elements, but for the 2nd list, i always get the related elements of the first item.
Do you have an idea ?
Thanks a lot for your help
This is because you only set:
$guidePois = $guide->getGuidePois($poi['id']);
once in the controller.
If you want it to work in the view, you need to insert this code right after the closing </h3>
<?php $guidePois = $guide->getGuidePois($poi['id']); ?>
So that $guidePois gets a new value in each iteration.
Complete view code:
<?php
foreach($req as $poi)
{
?>
<div class="news">
<h3>
<?php echo $poi['id']; ?>
<em>: <?php echo $poi['name']; ?></em>
</h3>
<?php
$guidePois = $guide->getGuidePois($poi['id']);
foreach($guidePois as $re)
{
?>
<h4>
<?php echo $re['id']; ?>:
<?php echo $re['name']; ?>
</h4>
<?php
}
?>
</div>
<?php
}
?>

mysql Simple Query + if

Seems like I'm not able to do a simple query.
What I want to achieve is all the results that have 'best2' value '1' so the div will be attached to only those results.
Right now , the div 'badge-best2div' attaches to ALL the products.
I don't know what I'm missing out.
<?php $show = true; ?>
<?php
$roman = Doctrine_Query::create()->from("Product")
->where("status = 1")
->andWhere("site_id = ? ", SITE_ID)
->andWhere("best2 = 1")
->fetchOne(array(), Doctrine_Core::HYDRATE_ARRAY);
?>
<?php if ($product->getIsTop() && !isset($hide_badge_top)): $show = false;?>
<div class="badge-top"></div>
<?php endif; ?>
<?php if ($roman['best2']){
$show = false; ?>
<div class="badge-best2div"></div>
<?php } ?>
<?php if ($product->getIsBestBuy() && !isset($hide_badge_bestbuy) && $show): ?>
<div class="badge-bestbuy"></div>
<?php endif ; ?>
got it working using
<?php if (($roman['best2'])==1){

this is my code. I want my search engine to turn the results into links to another page. idk how to

<?php
require_once 'db/connect.php';
if(isset($_GET['keywords'])) {
$keywords = $db->escape_string($_GET['keywords']);
$query = $db->query("
SELECT title
FROM articles
WHERE body LIKE '%{$keywords}%'
OR title LIKE '%{$keywords}%'
");
?>
<div class="result-count">
Found <?php echo $query->num_rows; ?> results
</div>
<?php
if($query->num_rows) {
while($r = $query->fetch_object()) {
?>
<div class="result">
<?php echo $r->title; ?>
</div>
<?php
}
}
}
It appears that all you are querying for is the article title? if this is all you need for the url then just replace the
<?php echo $r->title; ?>
with
<?php echo $r->title; ?>
however if you need an id or something else then you will need to ensure your database query is returning that data for example
SELECT ID, Title FROM...
then use
<a href="http://example.com/<?php echo $r->id; ?>">...

Issue sorting multidimensional array

Im having this issue with this filter of a site that im developing, basically i need to put all the categories together:
enter image description here
I need to put all the categories together, that means that all the "sistema operativo" and "disco duro" options should be together, not at the end of the list (pictured). I tried to achieve this with an array_push() and the in_array function, but at the end it just displays again these last options.
Here is my code:
<?php
$filterTitle = array();
foreach($resultFiltro as $filtros){ // titulo de categoria
if (!empty($_SESSION['filterId'])){
$resultDatos = filtroCategoriasDatos($filtros['id_padre']);
$resultFiltroDos = filtroDatosEspecificosFiltros($filtros['id'], $in[0]);
}else{
$resultDatos = filtroCategoriasDatos($filtros['id_caracteristica']);
$resultFiltroDos = filtroDatosEspecificos($filtros['id_caracteristica'], $in[0]);
}
<div class="grupo_filtro">
<?php
//if(!in_array($resultDatos[0]['titulo'], $filterTitle)){ ?>
<div class="titulo_filtro">
<?php echo $resultDatos[0]['titulo'];?>
</div>
<?php array_push($filterTitle, $resultDatos[0]['titulo']);?>
<?php //} ?>
<div class="con_filtros_filtro">
<?php foreach($resultFiltroDos as $select){ ?>
<div class="filtro atributo <?php echo $class;?>" titulopadre="<?php echo $resultDatos[0]['titulo'];?>" id="<?php echo $select['id'];?>">
<?php echo $select['titulo'];?>
</div>
<?php } ?>
</div>
</div>
<?php
} ?>
i dont know if this can be fixed sorting the recordset in some way or if there is other trick that can help me with this.
thanks in advance.
I think it could be your solution
<?php
$filterTitle = array();
foreach($resultFiltro as $filtros){ // titulo de categoria
?> <div class="grupo_filtro"> <?php
if (!empty($_SESSION['filterId'])){
$resultDatos = filtroCategoriasDatos($filtros['id_padre']);
$resultFiltroDos = filtroDatosEspecificosFiltros($filtros['id'], $in[0]);
?>
<div class="titulo_filtro">
<?php echo $resultDatos[0]['titulo'];?>
</div>
<?php array_push($filterTitle, $resultDatos[0]['titulo']);
}else{
$resultDatos = filtroCategoriasDatos($filtros['id_caracteristica']);
$resultFiltroDos = filtroDatosEspecificos($filtros['id_caracteristica'], $in[0]);
?>
<div class="con_filtros_filtro">
<?php foreach($resultFiltroDos as $select){ ?>
<div class="filtro atributo <?php echo $class;?>" titulopadre="<?php echo $resultDatos[0]['titulo'];?>" id="<?php echo $select['id'];?>">
<?php echo $select['titulo'];?>
</div>
<?php } ?>
</div>
</div>
<?php
}} ?>
The problem was in the function. I added an order by and it was fixed. Thank guys for your help.
here i attach the function
function filtroDatosEspecificosFiltros($datoPadre, $in=""){
global $db;
if($in != ""){
$filtroCategoriaDos = "SELECT p.titulo, pc.id_atributo, pc.id_caracteristica, p.id, pc.id_producto FROM principal p INNER JOIN producto_caracteristica pc WHERE p.id=".$datoPadre." AND p.id=pc.id_atributo AND visible=1 AND pc.id_producto IN (".$in.") group by pc.id_atributo";
}else{
$filtroCategoriaDos = "SELECT p.titulo, pc.id_atributo, pc.id_caracteristica, p.id, pc.id_producto FROM principal p INNER JOIN producto_caracteristica pc WHERE p.id=".$datoPadre." AND p.id=pc.id_atributo AND visible=1 group by pc.id_atributo";
}
$resultDatos = $db->getAll($filtroCategoriaDos);
usort($resultDatos, function ($elem1, $elem2) {
return strcmp($elem1['titulo'], $elem2['titulo']);
});
return $resultDatos;
}
thanks for all the help.

Categories