I have a quiz management system and need to fetch the data from the database and displaying the data one by one on clicking next button.
I want to use ajax to insert data into database after clicking next button by using file read and write function.
$sql=mysqli_query($con,"SELECT * FROM tbl_question WHERE setid='$set' AND status=1 ORDER BY RAND()");
while($sha=mysqli_fetch_array($sql)) {
<h4><? echo $sha['id'];?></h4>
here's simple way to do it
first get question from database then put a button to the next id
<?php
$rows = 0;
$id = isset($_GET['id'] ? (int) $_GET['id'] : 0;
$query = 'SELECT * FROM `tbl_question` WHERE `tbl_question`.`status` = 1 AND `tbl_question`.`id` = ? LIMIT 1';
$mysqli = new mysqli('localhost','user','password','database');
$stmt = $mysqli->prepare($query);
$stmt->bind_param('i',$id);
$stmt->execute();
$stmt->bind_result($id,$something,$something_else,$status);
while($stmt->fetch())
$rows++;
$stmt->close();
$mysqli->close();
if($rows === 0) {
echo 'qustion not found';
} else {
// output qustion
// button
echo '<a type="buttton" href="?id=' . $id + 1 . '">next</a>';
}
Related
I have a calendar application where users can submit calendar events(day, night, unavailable to the title column of my DB) for selected dates. More like an availability booking. I have a database table called events with id, username, name, title, date and status columns(all status =1). This function below outputs all event inputs by all users on the dates but i want to be able to output only data for the $_SESSION user. Thanks
function getEvents(date){
$.ajax({
type:'POST',
url:'functions.php',
data:'func=getEvents&date='+date,
success:function(html){
$('#event_list').html(html);
}
});
// Add date to event form
$('#event_date').val(date);
}
function getEvents($date = ''){
$date = $date?$date:date("Y-m-d");
$eventListHTML = '<h2 class="sidebar__heading">'.date("l", strtotime($date)).'<br>'.date("F d", strtotime($date)).'</h2>';
// Fetch events based on the specific date
global $db;
$stmt = $db->prepare("SELECT * FROM events WHERE date = ? AND username = ?");
$stmt->bind_param("ss", $date, $username);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows > 0){
$eventListHTML .= '<ul class="sidebar__list">';
$eventListHTML .= '<li class="sidebar__list-item sidebar__list-item--complete">Availability</li>';
$i=0;
while($row = $result->fetch_assoc()){ $i++;
$eventListHTML .= '<li class="sidebar__list-item"><span class="list-item__time">'.$i.'.</span>'.$row['title'].'</li>';
}
$eventListHTML .= '</ul>';
}
echo $eventListHTML;
}
I finally figured it out. It wasnt a problem with the Select statement. My session variable wasn't being accessed by my AJAX-called PHP script. Meaning I needed to set the sessions variable on both the page that the Ajax functions reside and my index page.
if ( is_null($_SESSION) || !$_SESSION )
{
session_start();
}//doesnt leave a warning that sesssion has been called previously
This way, the session_start() is being called for each request.
I have this modal jQuery AJAX:
$('#switch_modal').on('show.bs.modal', function (e) {
var rowid = $(e.relatedTarget).attr('data-id');
$.ajax({
type : 'post', // commented for this demo
url : 'pars.php', // commented for this demo
data : 'id='+ rowid,
success : function(data) {
$('.fetched-data').show().html(rowid); // show rowid for this demo
}
});
});
My mysql query:
$query="SELECT * FROM games WHERE winner='' ORDER BY amount DESC";
while ($row = $result->fetch_assoc()) {
My modal data-id:
<a href="#viewgame" data-toggle="modal" data-id="<?php echo $row['id'];?>"">
How can i do to use the var rowid like a PHP post? Something like that:
$id = $_POST['rowid'];
echo $id;
If i understand well this test your doing...
Your JavaScript rowid is the value.
The $_POST identifier is id.
Try this in your PHP:
$id = $_POST['id'];
echo $id;
You'll get the javascript rowid sent as a POST value (named as $_POST['id']) via ajax... And returning in data on ajax success.
$('.fetched-data').show().html(data);
So you'll have to use data in your jQuery html()... Wich is the echoed text.
-----
EDIT AFTER ACCEPTATION of this answer
(Based on your last comment)
So i have this query:
$query="SELECT * FROM games WHERE winner='' ORDER BY amount DESC";
if ($result = $conn->query($query)) {
while ($row = $result->fetch_assoc()) {
$gameid = $row['id'];
}
}
So i want to use $gameid variable into this query:
$sql = "SELECT * FROM games WHERE id='".$gameid."'";
I understand, that you want to get THE LAST matching full line where winner value is empty from games table.
No need for an ajax call...
No need for a second query.
Just do it:
$query="SELECT * FROM games WHERE winner='' ORDER BY amount DESC";
$result = $conn->query($query);
$row = $result->fetch_assoc();
for ($i=0;$i<sizeOf($row);$i++){ // This is the «size» (number of values) of one row, the last fetched.
echo $row[$i] . "<br>";
}
You'll get all your line values echoed...
This will be the LAST matching line fetched.
If you have many matching lines and want all results, do it like this:
$query="SELECT * FROM games WHERE winner='' ORDER BY amount DESC";
$result = $conn->query($query));
while ($row = $result->fetch_assoc()) { // While fetching, echo all values of one matching line.
echo "row id: " . $row['id'] . "<br>";
echo "values: <br>";
for ($i=0;$i<sizeOf($row);$i++){
echo $row[$i] . "<br>";
}
}
Notice that this script, that I suggest, will enlight you about the while fetch loop possible results. You'll have to work a little to have it displayed correctly on your page.
;)
I want to use AJAX/Javascript with PHP to carry out this following function and not have it all done by PHP itself. I have created a function which deletes an item from the MySQL database. It gives a validation to the user if they want to remove it by selecting Yes or No.
However, how would i change this so that it does the same function but the validation appears as a popupbox, and when Yes or OK is pressed it deletes the item from the database and reloads the page to show it has been removed.
I have provided the PHP code which relates to this function, but i want to specifically change this to using AJAX/Javascript as well in accordance with PHP.
<?php
// Delete Item Question to Admin, and Delete Product if they choose
if (isset($_GET['deleteid'])) {
echo 'Do you really want to delete product with ID of ' . $_GET['deleteid'] . '? Yes | No';
exit();
}
if (isset($_GET['yesdelete'])) {
// remove item from system and delete its picture
// delete from database
$id_to_delete = $_GET['yesdelete'];
$sql = mysqli_query($link,"DELETE FROM products WHERE id='$id_to_delete' LIMIT 1") or die (mysql_error());
// unlink the image from server
// Remove The Pic -------------------------------------------
$pictodelete = ("../inventory_images/$id_to_delete.jpg");
if (file_exists($pictodelete)) {
unlink($pictodelete);
}
header("location: inventory_list.php");
exit();
}
?>
<?php
// This block grabs the whole list for viewing
$product_list = "";
$sql = mysqli_query($link,"SELECT * FROM products ORDER BY date_added DESC");
$productCount = mysqli_num_rows($sql); // count the output amount
if ($productCount > 0) {
while($row = mysqli_fetch_array($sql)){
$id = $row["id"];
$product_name = $row["product_name"];
$price = $row["price"];
$stock = $row["stock"];
$date_added = strftime("%b %d, %Y", strtotime($row["date_added"]));
$product_list .= "Product ID: $id - <strong>$product_name</strong> - £$price - Stock: $stock - <em>Added $date_added</em> <a href='inventory_edit.php?pid=$id'>edit</a> • <a href='inventory_list.php?deleteid=$id'>delete</a><br />";
}
} else {
$product_list = "You have no products listed in your store yet";
}
?>
Your JS-File
$(document).ready(function() {
$('.delete').click(function() {
event.preventDefault();
var deleteId = $(this).parent().attr('id').val();
$.get('path/to/you/phpfile', {deleteId: deleteid}, function(data) {
var confirm = confirm(data);
if (confirm==true) {
$.get('path/to/you/phpfile', {yesdelete: 1});
}
});
});
});
In your PHP-File you have to remove header('Location: ...') and the block which grabs the list, wrap it in a function or etract it to another php file to call it with the a simliar ajax-command I used above. And you have to change th $product_list in the while-loop.
Product ID: <div id="$id">$id - <strong>$product_name</strong> - £$price - Stock: $stock - <em>Added $date_added</em> <a href='inventory_edit.php?pid=$id'>edit</a> • <div class="delete">Delete</div></div><br />
jQuery get the id-value of his parent-div. It´s actually not the best way, but something like this should work.
I have Database records which are loop echoes out, so it lists down in Divs each records info.
I'm trying to make a delete button, to delete the specific record from this page view. The loop number tracker variable $i also corresponds to the record ID, so loop 3 outputs a div containing the info of record ID 3.
So I just need to on click pass $i to a PHP function to then run the sql to drop the record with ID $i.
I'd like to do this all on the same page so I'm assuming I need ajax but thats where I get stumped. Also so I can have an alert "Are you sure" I've done ajax with jquery to ajax to php, but never this way.
PHP:
$webserver = 'localhost';
$administrator = 'root';
$password = '';
$db_name = 'cdb';
$db = mysqli_connect($webserver, $administrator, $password, $db_name)
or die('Error connecting');
if( isset($_REQUEST['page']))
{
$_SESSION['page'] = $_REQUEST['page'];
}
else
{
$_SESSION['page'] = 1;
}
$records_per_page = 8;
$query = " SELECT *
FROM cars, users
WHERE cars.dealerID = users.dealerID
AND users.username = '".$_GET['username']."'";
$result = mysqli_query($db, $query)
or die("Error in query: '$query'");
$row = mysqli_fetch_assoc($result);
$i = 1;
$start = ($_SESSION['page'] - 1) * $records_per_page;
$end = ($_SESSION['page']) * $records_per_page;
while($row = mysqli_fetch_assoc($result) and $i < $end)
{
$i++;
if( $i > $start )
{
<div>
delete
</div>
<div of magic n' fairies>
echo $row['informationandstuff'];
</div>
}
}
Delete function:
function deleteCar()
{
$delete = "DELETE FROM cars
WHERE carindex = '".$i"'";
}
I could post $i to another file and do it bt would prefer to keep to same page and allow for an are you sure js pop up.
If I'm understanding you correctly, one way to do this would be to store the $i variable in either an html data attribute, or an id (as you suggested). Then, use jquery to collect that id and pass it to the data property in the ajax call.
Sample list item (I'm assuming a heredoc here):
<div class="list-item" data-record-id="{$yourId}">your output</div>
Now, collect the id that the user clicked:
$('.list-item').click(function(){
//get item id
var recordId = $(this).data('record-id');
deleteRecord(recordId);
});
function deleteRecord(recordId) {
var recordData = 'recordId=' + recordId;
var request = $.ajax({
type: "post",
url: "the-php-page-you-use-for-async-calls",
data: recordData,
success: function(resp){
//show some validation that the record has been deleted
}
});
}
First, is it possible for when I insert a record onto my mysql table, a page is automatically generated using the new record in some way. EXAMPLE: My column "image" is on autoincrement, so my image names are always numbers. Furthermore, is it possible for when I insert a record, I automatically generate a page with my image name. So basically, I submit record 367, the image name is 367, and my site will automatically generate mysite.com/367? I want to go in more details but you get the point. Is it possible? If not, what's the closest thing possible?
Also, is there someway to automatically update my page periodically. Such as I set it so at 5pm, it'll automatically insert a code. 5:30pm, it'll insert a different code, which I preprogrammed to do. This is useful, for say I'm on vacation but I still want to update my site regularly.
Can you guys point me to any specific tutorial/terminology/methods/programs/codes/anything? All help would be appreciated!
EDIT: Code I have so far (just want to show to Nick)
<html>
<head>
<title>tgh</title>
</head>
<body>
<?php
$objConnect = mysql_connect("localhost","root","") or die(mysql_error());
$objDB = mysql_select_db("thegoodhumor");
$strSQL = "SELECT * FROM gallery";
if (!isset($_GET['Page'])) $_GET['Page']='0';
$objQuery = mysql_query($strSQL);
$Num_Rows = mysql_num_rows($objQuery);
$Per_Page = 16; // Per Page
$Page = $_GET["Page"];
if(!$_GET["Page"])
{
$Page=1;
}
$Prev_Page = $Page-1;
$Next_Page = $Page+1;
$Page_Start = (($Per_Page*$Page)-$Per_Page);
if($Num_Rows<=$Per_Page)
{
$Num_Pages =1;
}
else if(($Num_Rows % $Per_Page)==0)
{
$Num_Pages =($Num_Rows/$Per_Page) ;
}
else
{
$Num_Pages =($Num_Rows/$Per_Page)+1;
$Num_Pages = (int)$Num_Pages;
}
$strSQL .=" order by GalleryID ASC LIMIT $Page_Start , $Per_Page";
$objQuery = mysql_query($strSQL);
$cell = 0;
echo '<table border="1" cellpadding="2" cellspacing="1"><tr>';
while($objResult = mysql_fetch_array($objQuery))
{
if($cell % 4 == 0) {
echo '</tr><tr>';
}
if($cell == 2) {
echo '<td>RESERVED</td>';
} elseif ($cell == 3) {
echo '<td>The other cell</td>';
} else {
echo '<td><img src="https://s3.amazonaws.com/imagetitle/' . $objResult["Picture"] . '" />' .
$objResult["GalleryName"] . '</td>'; }
$cell++;
}
echo '</tr></table>';
?>
<br>
view more:
<?php
if($Prev_Page)
{
echo " <a href='$_SERVER[SCRIPT_NAME]?Page=$Prev_Page'>prev</a> ";
}
{
echo "|";
}
if($Page!=$Num_Pages)
{
echo " <a href ='$_SERVER[SCRIPT_NAME]?Page=$Next_Page'>next</a> ";
}
?>
</body>
</html>
<?php
mysql_close($objConnect);
?>
It sounds like you want a dynamic web page. To make a dymaic webpage I'd suggest using PHP which would interact with the mysql server.
For example, a user would visit 'mysite.com/info.php?image=367' and the php script would get the information 'image=367'. Your PHP script could do a select query against the mysql database 'SELECT paragraph FROM table WHERE image_id = 367' and then write that data out to the user's web browser.
As far as the user is concerned they just visited 'mysite.com/info.php?image=367', but in the background, PHP dynamically created the webpage content after it got that request.
More basic info about dynamic webpages: http://way.clicktracks.com/help/en/pr650/index.html?dynamicwebsiteshowtheywork.htm
Simple Intro to PHP:
http://www.tizag.com/phpT/
http://www.w3schools.com/php/php_intro.asp
Here is a head start I wrote for you, feel free to use it.
<?php
if (!isset($_GET['imageNumber']))
die("You must specify an image number");
$image_requested = mysql_real_escape_string($_GET['imageNumber']); //sanitizes input
$dbhost = 'localhost'; //TODO: Set this to the ip address of your mysql server if it is not on the same machine
$dbuser = 'root'; //TODO: Set the username you use to access your mysql db here
$dbpass = 'password'; //TODO: Set the password you use to access your mysql db here
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
$dbname = 'database_name_here'; //TODO: Set the database name here
mysql_select_db($dbname);
$query = "SELECT paragraph FROM table_name WHERE image_id = " . $image_requested; //TODO: Set table_name, column to get, and image_id to the correct column name
$result = mysql_query($query);
$row = mysql_fetch_array($result) or die(mysql_error());
echo "Here is the paragraph of text" . $row['paragraph']; //TODO: Set paragraph to the same column you retrieved 3 lines above.
mysql_close($conn);
?>
As for the second part of your question, it can also be done with PHP
<?php
$specifictime = strtotime("tuesday 3pm");
if (time("now") > $specifictime)
{
echo " its after 3pm on tuesday";
}
else {
echo " not 3pm on tuesday yet";
}
?>