I have a functioning foreach that I want to expand on. It's simple:
<ul>
<?
$sql_find = "SELECT DISTINCT(column_chosen) as Sec FROM column_a WHERE column_chosen NOT LIKE '' ";
$get_var = mysqli_query($db, $sql_find);
while ($r=mysqli_fetch_assoc($find_var)){
foreach($r as $newest_variable) {
echo '
<li>'.$newest_variable. '</li>';} }?>
</ul>
Let's say its html output is this:
<li>one</li>
<li>two</li>
<li>three</li>
I want to be able to get a specific variable ($newest_variable) and put it in $_SESSION or do other things, maybe alert it with javascript, etc, etc.
Question:
Is this possible with this structure? How could I get a specific variable $newest_variable?
For example, in the 2nd <li>, just get two and put into $_SESSION['result']
Any insight or direction is grealty appreciated.
<ul id="itemList">
<?
$sql_find = "SELECT DISTINCT(column_chosen) as Sec FROM column_a WHERE column_chosen NOT LIKE '' ";
$get_var = mysqli_query($db, $sql_find);
while ($r=mysqli_fetch_assoc($find_var)){
foreach($r as $newest_variable) {
echo '
<li>'.$newest_variable. '</li>';} }?>
</ul>
<script>
$('#itemList li').click(function() {
var index = $(this).index();
var text = $(this).text();
alert('Index is: ' + index + ' and text is ' + text);
});
</script>
Heres small code with JQuery, you can pass those variables to php with ajax and set as session, as well execute other functions you want :)
If you want to make an array of all the elements from the foreach, it's pretty simple:
<ul>
<?
$sql_find = "SELECT DISTINCT(column_chosen) as Sec FROM column_a WHERE column_chosen NOT LIKE '' ";
$get_var = mysqli_query($db, $sql_find);
while ($r=mysqli_fetch_assoc($find_var)){
foreach($r as $newest_variable) {
$newArray[] = $newest_variable; //Makes an array of all elements of the foreach
echo '
<li>'.$newest_variable. '</li>';
}
}
?>
</ul>
Now, the array $newArray will have all values of the foreach so that, for example, if you wanted the second element, you could use $newArray[1].
Related
I have a table consists of three columns :
id
author
message
Once the user clicks on the More Button the button passes the Count parameter to .load function. And then new data should display but it
displays a blank page.What am i doing wrong?
this is index.php:
<div id="comments">
<?php
$v=$db->prepare('select * from comments limit 2');
$v->execute();
$data=$v->fetchAll(PDO::FETCH_ASSOC);
foreach ($data as $row) {
echo "<div>".$row['author']."</div>";
echo "<div>".$row['message']."</div>";
echo "</br>";
}
?>
</div>
<input type="submit" name="" id="submit" value="More">
</body>
</html>
<script type="text/javascript">
$(document).ready(function(){
var commentCount=2;
$('#submit').click(function(){
commentCount=commentCount+2;
$('#comments').load('loadComments.php',{count:commentCount});
});
});
</script>
this is loadComments.php:
<?php
$db=new PDO('mysql:host=localhost;dbname=ajax',"root","");
$newCount=$_POST['count'];
$ex=$db->prepare('select * from comments limit $newCount');
$ex->execute();
$data=$ex->fetchALL(PDO::FETCH_ASSOC);
foreach ($data as $row) {
echo "<div>".$row['author']."</div>";
echo "<div>".$row['message']."</div>";
echo "</br>";
}
?>
EDİT:
If I use this way everything is ok.
$v=$db->prepare('select * from comments limit 3');
But I have checked count parametre inside loadComment.php
echo $newCount;
and I am able to get the value Its funny
The issue is because of using Single quoted strings (as ') instead of Double quote strings (as ") - as #mrunion mention in the comments
In PHP when using ' the inner string is not being evaluate in contrast to the " mark. So the statement of 'select * from comments limit $newCount' is been sent as is and the $newCount is not been evaluate as 2 or what ever int it hold.
Full explanation about PHP quote can be found here
I'm using a URL query string to filter MySQL search results. When a user clicks on one of the links the query along with another variable is passed to the application, which then builds and executes a SQL query to the database.
The filtering works - the user can filter by genre, platform and can also sort at the same time, but the problem is that every time they click on a link it adds another variable at the end of $query.
For example if the user types in example and selects as filter, the genre action, the query looks like this:
keywords=example&genre=action
But lets say they then click on the adventure genre, the query then looks like this:
keywords=example&genre=action&genre=adventure
Is there a way to get the query to replace a variable if it isalready set?
$query = mysql_real_escape_string(htmlentities(trim($_SERVER[QUERY_STRING])));
<div id="filter_nav">
<ul id="nav_form">
<li><h3 id="h3">Genre: </h3>
<li>Fighting</li>
<li>Role-Playing</li>
<li>Action</li>
</ul>
<ul id="nav_form">
<li><h3 id="h3">Platform: </h3>
<li>PS3</li>
<li>Xbox 360</li>
<li>Gamecube</li>
</ul>
</div>
';
echo '
<ul id="sorting_form">
<li><h3 id="h3">SORT BY: </h3>
<li>Title</li>
<li>Date</li>
<li>Rating</li>
</ul>
';
function search_results($keywords){
$returned_results = array();
$where = "";
$keywords = preg_split('/[\s]+/', $keywords);
$total_keywords = count($keywords);
foreach($keywords as $key=>$keyword){
$where .= "title LIKE '%$keyword%'";
if($key != ($total_keywords - 1)){
$where .= " AND ";
}
}
if (isset($_GET['platform']) && !empty($_GET['platform'])){
$platform = mysql_real_escape_string(htmlentities(trim($_GET['platform'])));
$where .= " AND platform='$platform'";
}
if (isset($_GET['genre']) && !empty($_GET['genre'])){
$genre = mysql_real_escape_string(htmlentities(trim($_GET['genre'])));
$where .= " AND genre='$genre'";
}
if (isset($_GET['order']) && !empty($_GET['order'])){
$order = mysql_real_escape_string(htmlentities(trim($_GET['order'])));
$where .= " ORDER BY $order DESC";
}
$results ="SELECT * FROM games WHERE $where ";
Using your code it can be done de-constructing the query string using parse_url and rebuilding it using http_build_query for every link.
However, personally I would just go for a form with 3 select boxes where the previously selected values are pre-selected.
You could put all your selection options in one multi-dimensional array and do a double loop.
Example:
<?php
$options = array(
"genre" => array("Fighting", "Role-Playing", ...),
...
);
foreach $options as $key => $value)
{
?>
<select name="<?php echo $key; ?>">
<?php
foreach ($value as $item)
{
// echo option for item and mark it selected if necessary
}
?>
</select>
<?php
}
?>
Modify every <a> tag like:
Fighting
to
Fighting
I.e remove '.$query.' part.
I am trying to show the results of the status of a bidding item using jQuery every second on every row in MySQL table, however only the result of the last row of the table is returned.
<?php
$query = "SELECT item, description, price, imageData, status, username, item_id FROM items";
$result = mysql_query($query) or die(mysql_error());
$z=0;
while($row = mysql_fetch_array($result))
{
//echo other columns here//
echo "<td><div id=status$z></div></td>";
?>
<script type=text/javascript>
function updatestatus(itemnum)
{
var url="updatestatus.php?auc=<?php echo $row['item_id']; ?>";
jQuery('#status' + itemnum).load(url);
}
setInterval("updatestatus(<? echo $z?>)", 1000);
</script>
<?
$z++;
}
?>
When I view source in the browser, the values for #status and auc for every row are correct. What am I missing here?
Here's the code for updatestatus.php
<?php
session_start();
require_once("connect.php");
$id = $_GET['auc'];
$getstatus = mysql_query("SELECT status FROM items WHERE item_id = '$id' ");
$row = mysql_fetch_array($getstatus);
echo"$row[status]";
?>
Everything looks good, save for the fact that it looks like you're creating multiple references to your updatestatus() function.
In Javascript, if you create multiple functions with the same name, calling them will only result in one of them running, usually the first or last one (depending on the implementation), so all the code you need to run in those functions needs to sit together in one function body.
If you're determined to use the code you've created, you'd need to throw all those update calls into one function body. There would be better ways to achieve what you need, but doing it with the code you've created, this would probably work better:
<?php
$query = "SELECT item, description, price, imageData, status, username, item_id FROM items";
$result = mysql_query($query) or die(mysql_error());
$javascript = "";
$z=0;
while($row = mysql_fetch_array($result))
{
//echo other columns here//
echo "<td><div id=status$z></div></td>";
// build the javascript to be put in the function later over here...
$javascript .= "jQuery('#status". $z ."').load('updatestatus.php?auc=". $row['item_id'] ."');";
$z++;
}
?>
...and then further down the page, create the javascript (modified slightly):
<script type=text/javascript>
function updatestatus()
{
<?php echo $javascript; ?>
}
setInterval(updatestatus, 1000);
</script>
So you're basically building up the Javascript that you'll need in your function, echoing it out inside the function body, and then setting the interval will call all that code, in this case, every second.
Like I said, there are definitely more efficient ways to achieve what you're trying to do, but this should work fine for now. I hope this makes sense, but please let me know if you need any clarity on anything! :)
I don't see that you're populating data using a incrementor. Is this supposed to be adding content to a page or replacing the content? from what it looks like it will just display one item, and then replace that one item with the next until it's done, which is why you see only the last row.
OR ...
the jquery update isn't being fed the $i variable .. change the function to
function updatestatus(itemnum) {
and then jquery echo to jQuery('#status' + itemnum).load(url);
then you can add the on-click/ or whatever to include the number
onclick='updatestatus("1")'
on the other hand you might be needing to pass the total number of items to the function and then creating an if there to cycle through them (not tested, but you get the idea i hope)
function updatestatus(numitems) {
var url = "";
var itemID = "";
for (i = 1; i <= numitems; i++) {
itemid = getElementById('#status'+numitems).getAttribute("itemID")
url="updatestatus.php?auc="+itemID;
jQuery('#status'+numitems).load(url);
}
}
setInterval("updatestatus()", 1000);
and the html element for "#status1" as created by the PHP should look like this:
<div id="status1" itemid="23455">
</div>
i'm having trouble with the serialize Jquery fonction.
Fist, i create my li element with a php script, my data are written in my database (with "id", "contenu", "position") and catch it in my html :
<article>
<ul id="columns">
<?php
$req01=mysql_query("SELECT * FROM mytable ORDER BY id DESC");
$i=0;
while ($res01=mysql_fetch_array($req01)){
$i++;
echo '
<li class="column" id="listItem_'.$res01["position"].'" draggable="true">
<p>'.$res01["contenu"].'</p>
</li>';
}
?>
</ul>
</article>
And here's my script
$(document).ready(function() {
$("#columns").sortable({
column : '.column',
update : function () {
var order = $('#columns').sortable('serialize');
$("#info").load('structure-reform.php?'+order);
//alert("Data Loaded: " + order);
}
});
});
</script>
And here the way i update my DB when my li order is changing
foreach ($_GET['listItem'] as $position => $item) :
$list[] = "$position, $item";
$req03=mysql_query("UPDATE mytable SET position='".$position."' WHERE id='".$item."'");
$result = mysql_query($req03);
endforeach;
The thing is that, when i reload my page, my list isn't sorted the right way...How can i do in order to keep my list in the last order ?
Thanks !
Your logic wasn't correct.
replace your javascript with this:
$("#columns").sortable({ update: function() {
var order = $(this).sortable("serialize");
$.post("structure-reform.php", order);
}
});
replace your list html with this
<li class="column" id="listItem_'.$res01['id'].'" draggable="true" rel="'.$perso.'">
<p>'.$res01["contenu"].'</p>
</li>';
replace your while loop with this
$listingCounter = 1;
foreach ($_POST['listItem'] as $recordIDValue) {
$query = "UPDATE structure SET position = " . $listingCounter . " WHERE id = " . $recordIDValue;
mysql_query($query) or die('Error, insert query failed');
$listingCounter = $listingCounter + 1;
}
echo 'If you refresh the page, you will see that records will stay just as you modified.';
You'll either want to save the order parameter in PHP - store it in $_SESSION, or, set a cookie on the user's computer and retrieve that to sort.
why you don't use jquery ajax using $.ajax() ? may be there is problem with serialize(), have you tried this one ?
$("#columns").sortable({
column : '.column',
update : function () {
var order = $(this).sortable('serialize');
$.ajax({
url : 'structure-reform.php',
type: 'GET',
data: order,
success:function(res){
alert('Data Loaded '+res);
}
});
}
});
and fot the first time, you should debug your parameter from ajax request, using php it quite simple
<?php
print_r($_GET);
?>
then you can do the rest when you have know what paramter are given there
It might be confusing and a bit difficult. I have a $fcomm variable that holds values as an array. This variable $fcomm is then assigned to an 'echo div' into another foreach loop. What I need is to make $fcomm loop itself while it gets assigned and echoed with each <div>. Here's the code...Thank you for any comments.
PHP:
for ($i2=0; $i2<$rowscheck; $i2++) {
//FRIEND QUERY COMMENTS
$fr_com = mysqli_query($connect,"SELECT * FROM comments WHERE name_main_id = '".$fcom[$i2]."' ORDER BY comm_id ASC ");
while ($rows_com = mysqli_fetch_array($fr_com)) {
extract($rows_com);
$fcomm[] = $rows_com['comment_main'];
}
}
if ($fr_check > 0 ) {
foreach ($friends_q2 as $fr_ids) {
$added_fr = "members/$fr_ids/userImg1.jpg";
if (!file_exists($added_fr)) {
$added_fr = "members/avatar/avatar.png" ;
}
echo "
<div id='frslide'>
<a href='javascript:window_usr($fr_ids)'>
<img src='".$added_fr."' height='68' width='66' hspace='2' vspace='16' id='fadd'/>
</a>
<span style='font-size:12px;position:relative;left:-71px;top:-1px;color:#ffffff; background-image:url(images/back_bar.png);'> ".$frnames2." </span>
</div>
<div id='frdiv' class='frdiv'>
<span style='font-size:12px;position:relative; left:-1px;top:72px;color:#ffffff;background-image:url(images/usr_main.png);'>
<a href='javascript:remusr($fr_ids)'>remove</a>
</span>
</div>
<div>".$fcomm;
}
}
$fcomm variable holds strings of comments from SQL. So when I add $fcomm[$i] or any loop variable to $fcomm it yields just single letters from comments - all I need is to make $fcomm print whole strings but different ones and the ones that correspond to proper each <div>. When I tried to place $fcomm in an inside loop - it prints strings but each string is the same...
You need to increase the index you're trying to retrieve from the fcomm array. Note the changes using $j variable.
if ($fr_check > 0 ) {
$j=0;
foreach ($friends_q2 as $fr_ids) {
$added_fr = "members/$fr_ids/userImg1.jpg";
if (!file_exists($added_fr)) {
$added_fr = "members/avatar/avatar.png" ;
}
echo "
<div id='frslide'>
<a href='javascript:window_usr($fr_ids)'>
<img src='".$added_fr."' height='68' width='66' hspace='2' vspace='16' id='fadd'/>
</a>
<span style='font-size:12px;position:relative;left:-71px;top:-1px;color:#ffffff; background-image:url(images/back_bar.png);'> ".$frnames2." </span>
</div>
<div id='frdiv' class='frdiv'>
<span style='font-size:12px;position:relative; left:-1px;top:72px;color:#ffffff;background-image:url(images/usr_main.png);'>
<a href='javascript:remusr($fr_ids)'>remove</a>
</span>
</div>
<div>".$fcomm[$j];
$j++;
}
}
Without knowing your code or column names etc., you probably need to populate $fcomm based on the friend IDs, and then echo out the corresponding comment in the foreach loop.
Something like this:
for ($i2=0; $i2<$rowscheck; $i2++) {
//FRIEND QUERY COMMENTS
$fr_com = mysqli_query($connect,"SELECT * FROM comments WHERE name_main_id =
'".$fcom[$i2]."' ORDER BY comm_id ASC ");
while ($rows_com = mysqli_fetch_array($fr_com)) {
extract($rows_com);
// populate $fcomm sub-array using the ID used to select
// them, i.e. $fcom[$i2]
$fcomm[ $fcom[$i2] ][] = $rows_com['comment_main'];
}
}
if ($fr_check > 0 ) {
foreach ($friends_q2 as $fr_ids) {
$added_fr = "members/$fr_ids/userImg1.jpg";
if (!file_exists($added_fr)) {
$added_fr = "members/avatar/avatar.png" ;
}
echo "<div id='frslide'>...</div>";
// echo out the right $fcomm depending on the ID, $fr_ids
foreach ($fcomm[$fr_ids] as $comment) {
echo '<div>', $comment, '</div>';
}
}
}