PHP array output to a javascript function - php

I am trying to connect a database with php and display result dynamically using javascript.
Here's What i am trying to do -
<?php
function mainMenu($q){
$res=array();;
$q->setFetchMode(PDO::FETCH_NUM);
while($r = $q->fetch()){
array_push($res, "
<li>
<a class='gn-icon ".mysql_real_escape_string($r[0])."'>".mysql_real_escape_string($r[1])."
</a>
</li>");
}
return $res;
} ?>
Now here is the html , which definitely works
<ul id="sidemenu" class="gn-menu">
<?php
$a=mainMenu($q);
foreach ($a as $value) {
echo $value;
}
?>
</ul>
but when i try this -
<script>
$('#sidemenu').html(<?php
$b=mainMenu($q);
foreach ($b as $value) {
echo "$value";
}
?>);
</script>
It doesnt work the, i just see blank space in my source and nothing is printed in the list, can anyone tell me where i am going wrong...

<?php
function mainMenu($q) {
$res=array();
$q->setFetchMode(PDO::FETCH_NUM);
while( $r = $q->fetch() ) {
array_push($res, "<li><a class='gn-icon ".mysql_real_escape_string($r[0])."'>".mysql_real_escape_string($r[1])."</a></li>");
}
return $res;
}
?>
<script>
$('#sidemenu').html("<?=implode('',mainMenu($q))?>");
</script>

you need to escape the single quote in your output using "Backslash",
<a class=\'gn-icon ".mysql_real_escape_string($r[0])."\'>".mysql_real_escape_string($r[1])." </a>
and you need use the .html like this,
.html('<?php $b=mainMenu($q); foreach ($b as $value) { echo $value;} ?>')

Related

How to fix Array to String conversion Bootstrap PHP?

i want to call sidebar menu items from database, but when i put the items from database to the which is i put in $menu, it returns error
<?php
$a=0;
foreach ($menu as $m ) {
$data[$a]=$m->menu_name;
// $menu .="<li class='active'><a href='#'><em class='fa fa-dashboard'> </em> ".$m->menu_name."</a></li>";
$menu.="<li><a href ='#'>".$data[$a]."</a></li>";
// echo $m->menu_name;
$a++;
}
?>
<?php echo $menu; ?>
I dont know what's wrong, any help will appreciate. Thanks
Variable name conflict in your case. You have $menu variable which is an array then again you are assigning the menu li element to same variable. change variable name for li element like
<?php
$a=0;
$menu1 = '';
foreach ($menu as $m ) {
$data[$a]=$m->menu_name;
$menu1.="<li><a href ='#'>".$data[$a]."</a></li>";
// $menu2.="<li><a href ='#'>".$m->menu_name;."</a></li>";
$a++;
}
?>
<?php echo $menu1; ?>
IT help to convert your data in array to encode string.
Code:
$menu_title= json_encode($menu);
<?php echo $menu_title; ?>
Or
<?php
echo implode("",$memu);
?>

Possible to reduce complexity of fetching and displaying data?

What I'm doing with the following code is fetching data from a table via PHP in order to display the data on a website.
$stri = "SELECT a, b, c, d, e, f FROM table";
$stat = $conn->prepare($stri);
if ($stat->execute()) {
while ($resu = $stat->fetch(PDO::FETCH_ASSOC)) {
foreach ($resu as $key=>$value) {
echo $value . "<br>";
}
echo "<br><br>";
}
}
However, it seems redundant to use two loops. Is there not a more efficient way to accomplish the same thing while allowing each item of each row to be handled independently?
I plan to do something like the following with it which is why I need to be able to handle the items independently.
if ($stat->execute()) {
while ($row = $stat->fetch(PDO::FETCH_ASSOC)) {
echo '<div class="row">';
foreach ($row as $key=>$value) {
echo '<div class=' .$key. '>';
if (empty($value)) echo '---<br>';
else echo $value;
echo '</div>';
}
echo '</div>';
}
}
However, it seems redundant to use two loops.
I cannot get what does it mean, but in all it's quite possible to reduce the complexity. For this you need to use PDO in the full force, not as a just a substitution for mysql_query(). A separation of concerns would also help
Get your data first in the form of array
$sql = "SELECT a, b, c, d, e, f FROM table";
$stmt = $conn->prepare($sql);
$stmt->execute();
$data = $stmt->fetchAll();
and then display it, somewhere inside the HTML part of the page
<?php foreach ($data as $row): ?>
<div class="row">
<?php foreach ($row as $key=>$value): ?>
<div class="<?=$key?>">
<?php if (!$value): ?>
---<br>
<?php else ?>
<?=$value?>
<?php endif ?>
</div>
<?php endforeach ?>
</div>
<?php endforeach ?>
function checking($val)
{
if(empty($val))
{
echo "---<br>";
}
else
{
echo $val;
}
}
$stri = "SELECT a, b, c, d, e, f FROM t";
try
{
$stat = $conn->prepare($stri);
$stat->execute();
$results = $stat->fetchAll(PDO::FETCH_ASSOC);
foreach ($results as $key=>$value)
{
echo implode('',array_map("checking",$value));
echo "<br><br>";
}
}
catch(Exception $e)
{
error_log($e->getMessage());
}
I do a little bit changed of your code. Instead of use if to catch error, I prefer to use try catch method.

Php Simple HTML DOM Parser - how to work with block repeats

I have blocks of <h2> but without attributes. After that go blocks of <p> without attributes.
Structure of this looked like this:
<h2></h2>
<p></p>
<p></p>
<p></p>
<h2></h2>
<p></p>
<p></p>
<h2></h2>
<p></p>
I'm using Php Simple HTML DOM Parser. I want to get data from <h2> block, after that get all <p> to another <h2> and so on.
But all <h2> must be connected to <p> which go after them. I thought to use key => value (example <h2> => <p>,<p>,... and another <h2>) but I am not sure how to do this.
Also, I know about next_sibling(), but don't know how to use it in loop. I did 2 variables, 1st has all <h2>, 2nd has <p>. I thought it can be useful for my goal. Here is the code:
$test = file_get_html('url');
foreach($test->find('h2') as $test2) {
echo $test2 . '<br>';
foreach($test->find('p') as $test3) {
echo $test3 .'<br>';
}
}
It's not super clear what you're looking for but here's an idea to get you started:
foreach($html->find('h2') as $el){
$h2 = $el;
while($el = $el->next_sibling()){
if('p' != $el->tag) break;
// do something
}
}
Answer of my question here. I hope it can help somebody!)
`foreach ($html->find('.div') as $div)
{
if(!$next=$div->next_sibling()) continue;
if($next->tag==='h2')
{
$h2 =$next;
echo $h2;
while ($h2 = $h2->next_sibling())
{
if(!$h2->tag=='p') break;
{
$p =$h2;
echo $p;
}
}
while ($h2 = $h2->next_sibling())
{
if(!$h2->tag=='table') break;
{
$tab =$h2;
echo $tab;
}
}
while ($h2 = $h2->next_sibling())
{
if(!$h2->tag=='ul') break;
{
$ul =$h2;
echo $ul;
}
}
}
else continue;
}`

PHP : Get 9 random value from array

I'm struggling to get 9 random values from an array, I have this php code which works fine but returns all the values. I need to only select 9 random ones with an foreach preferably.
<?php
foreach($gallerystreamobjects as $smallgallery) {
$smallgalleryArray = $smallgallery->GalleryPictures;
}
$arr = explode(",", $smallgalleryArray);
foreach($arr as $value)
{
?>
<a href="cms/uploads/<?php echo $value;?>" class="swipebox">
<div class="gallery-item-small" >
<div style="background-image:url('cms/uploads/<?php echo $value;?>')"></div>
</div>
</a>
<?php
}
?>
The function array_rand() will solve your problem:
$randomKeys = array_rand($arr, 9);
foreach($randomKeys AS $key){
$value = $arr[$key];
//do whatever you like
}
I managed to use an quick and easy way to do this. Not that its the right way, but ja, so I tried array_rand() but I kept on getting errors on it in its most basic way, I found out it was to do with the values actually going missing. Here is my current solution :
<?php
$smallgalleryArray = $gallerystreamobjects[0]->GalleryPictures;
$arr = explode(",", $smallgalleryArray);
shuffle($arr);
$count=0;
foreach($arr as $value) {
$count++;
if($count<10){
?>
<a href="cms/uploads/<?php echo $value;?>" class="swipebox">
<div class="gallery-item-small" >
<div style="background-image:url('cms/uploads/<?php echo $value;?>')"></div>
</div>
</a>
<?php
}
}
?>

whats the best way to echo a php tag inclusive in a while loop?

Edit |
This is a simple url...
The issue is I have to echo it in a while loop.
Which means I cant use php tags.
MY cancatenation sucks... I tried it for hours (noob) Please help
The issue is I have to echo it in a while loop. Which means I cant use php tags.
It doesn't mean that.
<?php
while ($condition) {
?>
Edit |
<?php
}
?>
(But if you have a list of links, then use list markup (ul/ol/li) not | characters).
try something like this
echo 'Edit'
It's pretty simple:
<?php
While(condition){
?>
Edit
<?php
}
?>
I would suggest to "prepare" the whole element in php. Something like this:
foreach ($arr as $key) {
print 'Edit';
}
<?php
while ($condition) {
echo 'Edit';
}
?>
You can also use heredoc syntax.
Sidenote, I would collect them all and echo it out once in the end
$text = '';
while ($foo) {
$text .= 'Edit';
}
echo $text;
// or heredoc
$text = '';
while ($foo) {
$text .= <<<_HTML
Edit
_HTML;
}
echo $text;
// or array
while ($foo) {
$data[] = 'Edit';
}
if(!empty($data)){
echo '<p>'.implode('</p><p>',$data).'</p>';
}
if it is a template file in php then always use this type of syntax
code:
<?php
$i=0;
while($i<10) : ?>
<div><?php echo $i;?></div>
<?php
$i++;
endwhile;?>

Categories