I have a database with 100 rows. I have a button that shuffle those id's and print out 3 random ids.
HTML
<form method="post">
<button>Shuffle</button>
</form>
PHP
$sql = "SELECT id, description FROM fantasies_original ORDER BY RAND ( ) LIMIT 3";
$res = $mysqli->query($sql);
//print($res);
if ($res->num_rows > 0) {
// output data of each row
while($row = $res->fetch_assoc()) {
echo "Store Number: " . $row["id"]. "<br>" .
"Description: " . $row["description"]. "<br><br>";
}
} else {
echo "0 results";
}
I would like to visualize the counter. So when I press the button I can see the number of the id there is loop through in the database. I have been looking everywhere to find a library that could do the job.
Does anybody knows a library or have a suggestion how to do that?
Related
I'm having a few problems with my "architecture". I'm really rusty in this field.
So the code below is basically PHP that reads a database table and prints row by row (columns are "name" (text), and "votes" (int) ) with a button near each row which is named by the "name" column as in the table.
Very simple by now, works perfectly.
Now, each button should add +1 to a row in table in the database (to votes column), by the name of the button, simple, but since the number of buttons is not constant and is changing by the number of rows in each table (dynamic), I need to create a JS event that will get a button pressed with its name/value, and call a php function (I need specifically with functions) with the name as a variable (parameter), so it will add +1 to the votes where the name is the name pressed).
$allsql = "SELECT * FROM `voting` ORDER BY `voting`.`groupName` DESC, `voting`.`votes` DESC";
$result = mysqli_query($conn, $allsql);
if (mysqli_num_rows($result) > 0) {
echo '<form method="post" id="voting_area">';// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$name = $row["name"];
$votes = $row["votes"];
echo 'name: ' .$name. ' - votes: ' .$votes. ' <button type="button" name="'.$name.'" value="'.$name.'">'.$name.'</button><br>';
}
echo '</form>';
}
Please try and explain me specifically each code (JS, AJAX, PHP).
I am trying to put mysqli results in alert box. it just show "Already Scanned".
below is the code:
echo '<script language="javascript">';
$new_query = mysqli_query($connection, "SELECT * FROM `table` WHERE `id` = '$id' LIMIT 1");
while ($row = mysqli_fetch_array($new_query))
{
echo 'alert("Already Scanned");
location.href="javascript:history.back()"';
}
echo '</script>';
how can i put MYSQLI fetch array results in alert box?
From your comments, I have understood that this is what you want:
Replace the echo command on line 8 with this:
echo 'alert("ID: ' + $row["id"] + ', name: ' + $row["name"] + ', mobile: ' + $row["mobile"] + '"); location.href="javascript:history.back()"';
This will display all the data you desire to display in the alert box. I understand that this is probably what you want to do right now. Correct me if you wished to do something else.
It isn't the prettiest solution, though.
I am building a site in which users have the ability to write post's and other users could comment on these posts.
By now I managed to create a div that contain the comment's that are posted, I have a "Like" button(not functional at this moment) and I have a "Comment" button that I want to trigger a small window that will open to recieve text from the user(the comment) and add it to my comment table(tblcomments).
The comment button has the same ID of the post it refers to(I built it that way when I echo'ed the page from php and everything sits in the same div). but I can't seem to find a way to pop-up that comment window to recieve the comment from the user and update my table with a comment for this specific post.
The section of the page that contains the comments is being refreshed every 5 seconds so adding a simple text field to the div is imposible cause it will get reset every 5 seconds.
that is how it looks on the page right now:
And that's the code that generate each and every post like this one on my main page while querying my DB:
<?php
include 'connectDB.php';
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
$hash = mysqli_escape_string($conn, $_SESSION['login_user']);
$resultfr = mysqli_query($conn, "SELECT distinct U.userName,concat(U.firstName,' ',U.lastname) as fullName FROM tblUser U inner join tblfriendswith FW on FW.userName1=U.userName or FW.userName2=U.userName where U.userName!='$hash'");
$uName="";
if($resultfr!= FALSE){
while($row2 = mysqli_fetch_array($resultfr)){
$uName= $uName.$row2['userName']." ";
}
}
$result = mysqli_query($conn, "SELECT U.userName,concat(U.firstName,' ',U.lastname) as fullName,MONTHNAME(P.postDate) as dateM, DAY(P.postDate) as dateD, YEAR(P.postDate) as dateY, P.postID, P.content FROM tblUser U inner join tblPost P on P.userName=U.userName where U.userName in ('$uName','$hash') order by P.postDate desc");
if($result!= FALSE){
echo "<div class='forPosts'>";
while($row = mysqli_fetch_array($result)){
$fullName = $row['fullName'];
$day=$row['dateD'];
$month=$row['dateM'];
$year=$row['dateY'];
$content = $row['content'];
$postID=$row['postID'];
echo "<div class=\"divStyle2\"><span class=\"myText2\">Posted by " .$fullName." - ".$day." ".$month." ".$year."</span><br><div class=\"divStyle\">".$content."</div>";
echo "<br><button class=\"myButton\"> <span class=\"glyphicon glyphicon-heart pull-left\"></span> Like</button>   <button class=\"myButton\"><span class=\"glyphicon glyphicon-comment pull-left\"></span>  Comment</button>   <button class=\"myButton\" name=\"clickB\" id=\"".$postID."\"><span class=\"glyphicon glyphicon-triangle-bottom pull-left\"></span>  Show/hide comments</button></div>";
//echo "<p class=\"alignW\"><input class=\" col-sm-5\" type=\"text\" name=\"comment\" id=\"".$postID."\" placeholder=\"Write a comment\"></div>";
$result2 = mysqli_query($conn, "SELECT C.postID, C.commentID, C.userName, C.content,concat(U.firstName,' ',U.lastname) as fullN,MONTHNAME(C.commentDate) as dateM, DAY(C.commentDate) as dateD, YEAR(C.commentDate) as dateY FROM tblUser U inner join tblComment c on U.userName=C.userName where C.postID=$postID order by C.commentDate desc");
if($result2!= FALSE){
echo"<div class='forComments'>";
while($row2 = mysqli_fetch_array($result2)){
$fullN = $row2['fullN'];
$day2=$row2['dateD'];
$month2=$row['dateM'];
$year2=$row2['dateY'];
$content2 = $row2['content'];
echo "<div class=\"divStyle2\" id=\"".$postID."\"><span class=\"glyphicon glyphicon-comment\" ></span><span class=\"myText3\"> " .$fullN. " : ".$content2."</span></div>";
}
}echo"</div>";
}
echo "</div>";
}
echo" <script>
$(document).ready(function(){";
echo" $(\"button[name=clickB]\").click(function() {
link = $(this).attr('id');
$('div[id=\"'+link+'\"]').toggle();
$(\"span\", this).toggleClass(\"glyphicon glyphicon-triangle-bottom glyphicon glyphicon-triangle-top\");
});";
echo"}); </script>";
?>
I use mysqli and xampp.
I would be grateful if someone could help me to achieve my task.
Thank you!
Tom
I am trying to figure out how to parse the SQL data I pulled using PHP to a javascript file.
I need to store the PHP array into java because I have a graph that uses a javascript array to populate the data.
Right now I have a button that refreshes my graph data, and when it is clicked it calls this javascript that's included in my main HTML file:
button.js
$(function(){
$('#refreshchart').click(function() {
var chart = $('#chart').highcharts();
chart.series[0].setData(dataarray);
});
});
The Java array "dataarray" needs to be pulled from a SQL database.
I have a PHP script that pulls the required data from the database.
Here is my PHP script:
query.php
<?php
include 'dbcon.php';
$query0 = "SELECT count(*) FROM test WHERE ans=0";
$query1 = "SELECT count(*) FROM test WHERE ans=1";
$query2 = "SELECT count(*) FROM test WHERE ans=2";
$query3 = "SELECT count(*) FROM test WHERE ans=3";
$query4 = "SELECT count(*) FROM test WHERE ans=4";
$query5 = "SELECT count(*) FROM test WHERE ans=5";
$query6 = "SELECT count(*) FROM test WHERE ans=6";
$query7 = "SELECT count(*) FROM test WHERE ans=7";
$query8 = "SELECT count(*) FROM test WHERE ans=8";
$query9 = "SELECT count(*) FROM test WHERE ans=9";
$result0 = $mysqli->query($query0) or die($mysqli->error.__LINE__);
$result1 = $mysqli->query($query1) or die($mysqli->error.__LINE__);
$result2 = $mysqli->query($query2) or die($mysqli->error.__LINE__);
$result3 = $mysqli->query($query3) or die($mysqli->error.__LINE__);
$result4 = $mysqli->query($query4) or die($mysqli->error.__LINE__);
$result5 = $mysqli->query($query5) or die($mysqli->error.__LINE__);
$result6 = $mysqli->query($query6) or die($mysqli->error.__LINE__);
$result7 = $mysqli->query($query7) or die($mysqli->error.__LINE__);
$result8 = $mysqli->query($query8) or die($mysqli->error.__LINE__);
$result9 = $mysqli->query($query9) or die($mysqli->error.__LINE__);
$row0 = $result0->fetch_row();
$row1 = $result1->fetch_row();
$row2 = $result2->fetch_row();
$row3 = $result3->fetch_row();
$row4 = $result4->fetch_row();
$row5 = $result5->fetch_row();
$row6 = $result6->fetch_row();
$row7 = $result7->fetch_row();
$row8 = $result8->fetch_row();
$row9 = $result9->fetch_row();
echo "Number of people that chose A: ", $row1[0];
echo "<br>Number of people that chose B: ", $row2[0];
echo "<br>Number of people that chose C: ", $row3[0];
echo "<br>Number of people that chose D: ", $row4[0];
echo "<br>Number of people that chose E: ", $row5[0];
echo "<br>Number of people that chose F: ", $row6[0];
echo "<br>Number of people that chose G: ", $row7[0];
echo "<br>Number of people that chose H: ", $row8[0];
echo "<br>Number of people that chose I: ", $row9[0];
echo "<br>Number of people that chose J: ", $row0[0];
$array = array($row1[0],$row2[0],$row3[0],$row4[0],$row5[0],$row6[0],$row7[0],$row8[0],$row9[0],$row0[0]);
echo json_encode($array);
?>
Now I know that I am going to have to encode the PHP array using json so that it is properly formatted and that I am probably going to have to use AJAX to call the PHP script to get the data.
This is where I am getting stuck, I am not sure how to grab the results and parse them into the java array so that the graph can be updated with the results in the SQL database.
Any help would be much appreciated!
Thanks,
Christopher
If you want to call your php-code via ajax try:
$(function(){
var chart = $('#chart').highcharts();
$('#refreshchart').click(function() {
$.ajax({
type: "GET",
url: "some.php",
success: function(data) {
chart.series[0].setData($.parseJSON(data));
}
});
});
});
Just set "some.php" to your php-filename.
<script>
var contants = <?php echo json_encode($array); ?>
</script>
And then transform it into an array. jQuery's $.parseJSON(string) might help.
If possible, avoid writing dynamic JavaScript in your code, use webservices for this, you can get this data through AJAX call using jQuery for example.
$.ajax({
url: "query.php",
data: { json: "on" },
}).done(function(data) {
console.log(data);
alert("found " + data.length + " elements" + "\n" + "first one: " + data[0].name + " = " + data[0].total);
});
I would prefer to write like this:
<?php
include 'dbcon.php';
$query =
"SELECT 'A' AS name,count(*) AS total FROM test WHERE ans=0 UNION " .
"SELECT 'B' AS name,count(*) AS total FROM test WHERE ans=1 UNION " .
"SELECT 'C' AS name,count(*) AS total FROM test WHERE ans=2 UNION " .
"SELECT 'D' AS name,count(*) AS total FROM test WHERE ans=3 UNION " .
"SELECT 'E' AS name,count(*) AS total FROM test WHERE ans=4 UNION " .
"SELECT 'F' AS name,count(*) AS total FROM test WHERE ans=5 UNION " .
"SELECT 'G' AS name,count(*) AS total FROM test WHERE ans=6 UNION " .
"SELECT 'H' AS name,count(*) AS total FROM test WHERE ans=7 UNION " .
"SELECT 'I' AS name,count(*) AS total FROM test WHERE ans=8 UNION " .
"SELECT 'J' AS name,count(*) AS total FROM test WHERE ans=9";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
$rows = $result->fetch_all(MYSQLI_ASSOC);
$print_json = !empty($_GET['json']) && $_GET['json']=='on'; // your content negotiation logic here
if ($print_json) {
header('Content-Type: application/json');
echo json_encode($rows);
} else {
foreach ($rows as $row) {
echo "Number of people that chose {$row['name']}: {$row['total']}";
}
}
This way you have more control and a cleaner code. I think you code improve SQL, though.
this code is working
var str_array=[];
function something()
{
str_array= <?php echo json_encode($array); ?>;
alert(str_array);`
}
in my code i'm showing drop down select field list base on user school choice. for example -
if user choose 'School of Economics' from drop down list, i'm showing in another drop down list just the relevant lanes (based on a mysql query).
to do this i have 5 div's, on for etch school:
<div id='a'>
<span><label>Lane</label></span>
<?php
$sql = "SELECT lane_name FROM lane WHERE `lane_school_id` = 1 ORDER BY `lane_name` ASC";
$result = mysql_query($sql);
echo "<select name='lane_name'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['lane_name'] ."'>" . $row['lane_name'] ."</option>";
}
echo "</select>";
?>
</div>
<div id='b'>
<span><label>Lane</label></span>
<?php
$sql = "SELECT lane_name FROM lane WHERE `lane_school_id` = 2 ORDER BY `lane_name` ASC";
$result = mysql_query($sql);
echo "<select name='lane_name'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['lane_name'] ."'>" . $row['lane_name'] ."</option>";
}
echo "</select>";
?>
</div>
i have a listener to show just the right 'lane' div when user chooses school and hide all other 'lane' div's:
$(document).bind('pageinit', '#indexPage', function(){
$("#a").show();
$("#b").hide();
$("#c").hide();
$("#d").hide();
$("#e").hide();
//this will call our toggleFields function every time the selection value of School field changes
$("#school").change(function () {
toggleFieldsA();
toggleFieldsB();
toggleFieldsC();
toggleFieldsD();
toggleFieldsE();
});
});
function toggleFieldsA() {
if ($("#school").val() == 'School of Economics'){
$("#a").show();
}
else
$("#a").hide();
}
function toggleFieldsB() {
if ($("#school").val() == 'School of Computer Science')
$("#b").show();
else
$("#b").hide();
}
the problem: when user submit the form, i get the wrong 'lane_name' from POST array. i'm getting the last school selected lane value (that is hidden from the user) and not the user selected lane name , plz help
You need to give each <select> element a unique name, otherwise the last element with a particular name will be the only one you can access. PHP has no way of determining which of the 5 lane_name you are referring to.
To figure out what option set was selected you could make the first option blank: <option value=""></option>. You can add some logic to reset to the blank option when you hide/show the DIVs so only one of the lane_names will have any data in it.
The mysql_* is depreciated as of PHP 5.5.0. You should consider switching to mysqli.