Not sure if this is possible but here goes, I have a basic PDO query that stores the results in a array.
<?php
// configuration
$dbtype = "";
$dbhost = "";
$dbname = "";
$dbuser = "";
$dbpass = "";
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$title = 'PHP AJAX';
// query
$sql = "SELECT * FROM thankyou";
$q = $conn->prepare($sql);
$q->execute(array($title));
$q->setFetchMode(PDO::FETCH_BOTH);
// fetch
while($r = $q->fetch()){
echo"<br>";
print_r ($r);
}
?>
Now the bit I can't get my head around, I have also never used JavaScript. Can I rotate through the results to show one at a time for 5-10 seconds then show another? It can be random or in order, I'm not fussed. I found this, which works, but can't figure out how to get the array into it. I am aware one is client side and one is server side.
<script type="text/javascript">
var rotatingTextElement;
var rotatingText = new Array();
var ctr = 0;
function initRotateText() {
rotatingTextElement = document.getElementById("textToChange");
rotatingText[0] = rotatingTextElement.innerHTML; // store the content that's already on the page
rotatingText[1] = "need to write PDO array here";
setInterval(rotateText, 5000);
}
function rotateText() {
ctr++;
if(ctr >= rotatingText.length) {
ctr = 0;
}
rotatingTextElement.innerHTML = rotatingText[ctr];
}
window.onload = initRotateText;
</script>
and this is were the results are shown
<span id="textToChange">this is were the result is displayed</span>
If I need to do it a totally different way, it's not a problem if someone can point me in the correct direction.
If you're not so familiar with JavaScript, I also suggest using some JS library for the task. In fact, Prototype.js has a class exactly for this purpose: http://prototypejs.org/doc/latest/ajax/Ajax/PeriodicalUpdater/index.html
A working example: http://www.tutorialspoint.com/prototype/prototype_ajax_periodicalupdater.htm
i decided to use AJAX to call a seprate PHP page in the end and works fine this is the updated page.
<script type="text/javascript">
$(function() {
getStatus();
});
function getStatus() {
$('div#status').load('thankyou.php')//Thankyou being the page the query is on
setTimeout("getStatus()",5000);//refreshes every 5 seconds
}
</script>
The query itself is a standard PDO
$query = $db->query("SELECT * FROM `thankyou` ORDER BY RAND() LIMIT 1
Thanks for the pointers all.
Related
I have a google maps web application for a game where the user will click a google map marker, make a selection in the window that pops up and click submit. It uses AJAX to update the database with information selected by the user. The database is pre-populated with names of the markers and GPS coordinates, which are loaded. The markers are also placed accordingly upon load via XML.
I'm having trouble updating one row in my DB called quest with the user selected information when it's submitted. Currently, a user can select a marker and submit a quest, but it won't update the DB at all. I'm unsure on the correct WHERE statement to use. Here's my current SQL statement, I'm attempting to update a row called quest.
mysqli_query($con, "UPDATE markers SET quest= '$questName' WHERE markerName = '$markerName'");
This is what happens when the submit button is pressed.
if (document.getElementById("questType").value ==
"quest1") { //if quest1 is selected upon submission
alert("quest1");
var markerName;
var questName = "Quest 1";
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "ajax.php?questName=" + questName + "&markerName=" + markerName, true);
xmlhttp.send(); //Sending the request to the server
ajax.php
<?php
include("connect.php");
require("call2.php");
$markerName = mysqli_real_escape_string($con, $_GET['markerName']);
$questName = mysqli_real_escape_string($con, $_GET['questName']);
$stmt = $con->prepare("UPDATE markers SET quest = $questName WHERE markerName = $markerName");
$stmt->bind_param($questName, $markerName);
$stmt->execute();
$stmt->close();
?>
Here is my relevant call file as well.
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);
include('connect.php');
$query = "SELECT * FROM markers WHERE 1"; // Select all the rows in the markers table
$result = mysqli_query($con, $query);
if (!$result) {
die('Invalid query: ' . mysqli_error($con));
}
// Iterate through the rows, adding XML nodes for each
while ($row = mysqli_fetch_assoc($result)) {
global $dom, $node, $parnode;
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("markerName",
$row['markerName']);
$newnode->setAttribute("quest", $row['quest']);
$newnode->setAttribute("lat", $row['lat']);
$newnode->setAttribute("longg", $row['longg']);
}
header("Content-type: text/xml");
echo $dom->saveXML();
Sorry if this is a lot, I think the problem is i'm not assigning a value to markerName. I don't get any errors, however when I hover over the ajaxphp in the network tab on chrome it looks like it's getting the questName but markerName remains undefined.
Here's where it's loading things in:
downloadUrl("call2.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("markerName"); //<------ here's where it's getting markerName
// var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("longg")));
var icon = customLabel[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
bindInfoWindow(marker, map, infoWindow, html);
}
});
I think I need to figure out a way to access name, but I'm unsure how to when it's local to the function which downloads the XML file.
connect.php
<?php
$con = mysqli_connect("localhost", "root", "", "pokestop-map");
?>
First of all, I think in some cases your Database Connection Credentials could be leaked if your Database is down and somebody is requesting ajax.php. If you want to use code in an production environment you should never leak errors to the client. Also I'm not sure if you're trying to add the Params to your Query through PHP's ability to evaluate variables in Strings, if so that is very unsecure and I would recommend you to read about Prepared Statements. Also I would recommend you to use PDO's (http://php.net/manual/de/book.pdo.php) instead of MySQLi but that's just a sidenote. I think the Problem here is that you don't bind your value to the Query. It's a long time ago that i've used MySQLi but I think you could do something like:
$stmt = $mysqli->prepare("UPDATE markers SET quest = ? WHERE markerName = ?");
$stmt->bind_param($questName, $markerName);
$stmt->execute();
$stmt->close();
Edit:
I would recommend you to look at ORM libraries which allow you to Map the Rows in a table to an object in PHP. There are a few of them out there like Doctrine or Idiorm. Working with Objects is much cleaner. But anyway I also wrote a little bit code which may help you, but I have to say its not tested.
DB.php (Holds an PDO in Singleton Pattern which will be used to communicate with the Database):
require_once('Config.php');
class DB {
private static $_instance = null;
private $_pdo;
private function __construct() {
try {
$this->_pdo = new PDO('mysql:host=' . Config::getDbHost() . ';dbname=' . Config::getDbName(), Config::getDbUser(), Config::getDbPass());
} catch(PDOException $e) {
die($e->getMessage());
}
}
public static function getInstance() {
if(!isset(self::$_instance)) {
self::$_instance = new DB();
}
return self::$_instance;
}
/**
* #return PDO
*/
public function getPdo()
{
return $this->_pdo;
}
}
Config.php (Holds the settings needed to connect to the Database, you can extend the Class and parse some kind of configuration file to fill the values if you want):
class Config
{
private static $_dbHost;
private static $_dbName;
private static $_dbUser;
private static $_dbPass;
/**
* #return mixed
*/
public static function getDbHost()
{
return self::$_dbHost;
}
/**
* #return mixed
*/
public static function getDbName()
{
return self::$_dbName;
}
/**
* #return mixed
*/
public static function getDbUser()
{
return self::$_dbUser;
}
/**
* #return mixed
*/
public static function getDbPass()
{
return self::$_dbPass;
}
}
With these classes you should be able to do the following:
<?php
require_once('DB.php');
$pdo = DB::getInstance()->getPdo();
$stmt = $pdo->prepare('UPDATE markers SET quest = :questName WHERE markerName = :markerName');
$stmt->bindValue('questName', $_GET['questName']);
$stmt->bindValue('markerName', $_GET['markerName']);
$stmt->execute();
As I said this is not tested, but it should work. Maybe you have to fix includes and Parameter Binding...
I am building a website and I can not figure out one thing. I need a script that checks if 10 seconds have past since load time, then it would run another PHP script. But I am not sure if it is possible. I have attached my attempt at this problem. Any ideas? Thanks in advance!
if (
<script type="text/javascript">
function viewplus(){
}
setTimeout(viewplus, 10000);
</script>
)
$query = "SELECT * FROM users WHERE id=" . $rws2['id_user'];
$result2 = mysqli_query($db, $query);
$rws2 = mysqli_fetch_array($result2);
$views_total = $rws2['views_total'] + 1;
$views_week = $rws2['views_week'] + 1;
$views_today = $rws2['views_today'] + 1;
$id = $rws2['id'];
$query = "UPDATE users SET views_total='$views_total',views_week='$views_week',views_today='$views_today' WHERE id='$id'";
mysqli_query($db, $query);
It is possible using jQuery like this:
Put your code in a php file and call it after 10 seconds after page load with
<script type="text/javascript">
// Check if the page has loaded completely
$(document).ready( function() {
setTimeout( function() {
$('#some_id').load('index.php');
}, 10000);
});
</script>
Example of updating a table and receiving a status message:
if (isset($_POST['id'])&&
isset($_POST['var'])){
$con = new mysqli("localhost", "my_user", "my_password", "world");
$id = $con->real_escape_string($_POST['id1']); //In our example id is INT
$var = $con->real_escape_string($_POST['var']);
$result = $con->query("UPDATE table SET value = '$var' WHERE id = $id);
(!$result) ? echo "Update failed!" : "Update succeeded";
}
This will load the output of your php file(Update filed or succeeded) in a element (this case one with id some_id).
Another way which I DO NOT recommend is using PHP's sleep() function PHP Documentation
I'd like to find a way of having a single page in the root of each of my web sections to hold all of the databae queries I'm calling.
I'm using a little script .....
<script type="text/javascript">
$(function() {
var availableTags = <?php include('fn-search-em.php'); ?>;
$("#quick-add").autocomplete({
source: availableTags,
autoFocus:true
});
});
</script>
.... to do SQL searches that appear as the user is typing. Similar to this ....
$sql = "SELECT * FROM stock_c_colours WHERE current_c_status = 'current' AND deleted = 'no'";
$result = mysqli_query($conn, $sql);
$results_list = array();
while($row = mysqli_fetch_array($result))
{
$colour_id = $row['id'];
$range_name = $row['range_name'];
$range_colour = $row['colour'];
$colour_code = $row['code'];
$p1 = $row['piece_size_1'];
$p2 = $row['piece_size_2'];
if($p1 > 1){
$p_mark = 'x';
}
else {
$p_mark = '';
}
$results_list[] = $range_name.' ('.$range_colour.' '.$colour_code.' '.$p1.$p_mark.$p2.') ID:'.$colour_id;
}
echo json_encode($results_list);
Echos a list in the form of a JSON array back to the text box and voila, a list. However, the site I'm working on at the moment has about 20 search boxes for various reasons scattered around (user request), does this mean I have to have 20 separate php function pages, each with their own query on, or can a single page be used?
I suspect the java needs modifying a little to call a specific function on a page of multiple queries, but I'm not good with Java, so some help would be greatly appreciated.
I did initially try adding ?action= to the end of the PHP address in the Java script, hoping a GET on the other end would be able to separate the PHP end into sections, but had no luck.
You need to change <?php include('fn-search-em.php'); ?>; to <?php $action = 'mode1'; include('fn-search-em.php'); ?>;.
Then in your fn-search-em.php file, use the $action variable to determine what kind of MySQL query you make.
For example:
if ($action == 'mode1')
$sql = "SELECT * FROM stock_c_colours WHERE current_c_status = 'current' AND deleted = 'no'";
else
$sql = "SELECT * FROM stock_c_colours WHERE current_c_status = 'mode1' AND deleted = 'no'";
You can do this with by creating a php file with a switch statement to control what code is executed during your Ajax call:
JS:
$.ajax({url: 'ajax.php', method: 'POST', async:true, data: 'ari=1&'+formData,complete: function(xhr){ var availableTags = JSON.parse(xhr.responseText);}});
PHP:
<?php
switch($_REQUEST['ari']){
case 1:
$sql = "SELECT * FROM stock_c_colours WHERE current_c_status = 'current' AND deleted = 'no'";
$result = mysqli_query($conn, $sql);
$results_list = array();
while($row = mysqli_fetch_array($result)){
$colour_id = $row['id'];
$range_name = $row['range_name'];
$range_colour = $row['colour'];
$colour_code = $row['code'];
$p1 = $row['piece_size_1'];
$p2 = $row['piece_size_2'];
if($p1 > 1){$p_mark = 'x';}
else { $p_mark = ''; }
$results_list[] = $range_name.' ('.$range_colour.' '.$colour_code.' '.$p1.$p_mark.$p2.') ID:'.$colour_id;
}
echo json_encode($results_list);
break;
case 2:
// another SQL Query can go here and will only get run if ARI == 2
break;
}
?>
This allows you to keep multiple AJAX handlers in the same file, you just need to pass the index for the desired handler when you make calls to the PHP file or nothing will happen.
So, I need to display 2 or 3 different images in a website, as simple parallax dividers for content.
I have an array of 4 images, so I'll be able to randomize without repeat them in the same page, althoug the random won't be that noticeable.
I've been lurking this for a while, and found these
Random Image Display, Without Repeat, with Javascript
<script language="javascript">
var imagesArray = [
'images/img-1.jpg',
'images/img-2.jpg',
'images/img-3.jpg',
'images/img-4.jpg',
'images/img-5.jpg',
];
var usedImages = {};
var usedImagesCount = 0;
function displayImage() {
var num = Math.floor(Math.random() * (imagesArray.length));
if (!usedImages[num]) {
document.canvas.src = imagesArray[num];
usedImages[num] = true;
usedImagesCount++;
if (usedImagesCount === imagesArray.length) {
usedImagesCount = 0;
usedImages = {};
}
} else {
displayImage();
}
}
</script>
(this was created to exhibit the image upon a click on a button, as it follows
<input onclick="displayImage();" type=button value="Click Here">
I tried to adapt it to my need, but the call on my page din't produce any results)
https://www.daniweb.com/programming/web-development/threads/266181/random-imageslinks-without-repeating
(this one, I couldn't quite understand why, but I wasn't able to apply the solution. not sure if it's the code or the way of calling the image that's wrong...)
http://www.utopiamechanicus.com/article/not-so-random-image-rotation-in-php-for-html-the-sequel/
<?php
// rotate images randomly but w/o dups on same page - format:
// <img src='rotate.php?i=0'> - rotate image #0 - use 'i=1'
// for second, etc
// (c) 2004 David Pankhurst - use freely, but please leave in my credit
$images = array(// list of files to rotate - add as needed
"img1.gif",
"img2.gif",
"img3.gif",
"img4.gif",
"img5.gif");
$total = count($images);
$secondsFixed = 10; // seconds to keep list the same
$seedValue = (int) (time() / $secondsFixed);
srand($seedValue);
for ($i = 0; $i < $total; ++$i) { // shuffle list 'randomly'
$r = rand(0, $total - 1);
$temp = $images[$i];
$images[$i] = $images[$r];
$images[$r] = $temp;
}
$index = (int) ($_GET['i']); // image index passed in
$i = $index % $total; // make sure index always in bounds
$file = $images[$i];
header("Location: $file"); // and pass file reference back
?>
(this one was supposed to work calling through:
<img src='mysite.com/rotate.php?i=0'>
but the images are still repeating themselves sometimes)
They didn't work for me, so I decided to start a new topic, because I'm really newbie (actually, I don't know writing nothing at all) at javascript, and can't figure out what's the best approach. I understood it would be something like randomize the items, assign each of them a position (a number, a character, a [i], etc), and then call for it in my php page. Could you guys please help me?
Not sure is that you want but this will give you randomized images (without repeat) on a page, every time different ones:
<?php
$img = array('img1.png', 'img2.png', 'img3.png', 'img4.png', 'img5.png', 'img6.png');
shuffle($img);
for($i=0; $i<3; $i++){
print '<img src="'.$img[$i].'"><br>';
}
?>
If you want to receive one image per call, one of the possible solutions is to use session:
image.php:
<?php
session_start();
function getImage() {
$img = array('img1.png', 'img2.png', 'img3.png', 'img4.png', 'img5.png');
shuffle($img);
foreach($img as $key => $val) {
if (!is_array($_SESSION['img'])) {
return $val;
} elseif (count($_SESSION['img']) >= count($img)) {
$_SESSION['img'] = array();
}
if (is_array($_SESSION['img']) && !in_array($val, $_SESSION['img'])) {
return $val;
}
}
}
?>
page.php:
<?php
include 'image.php';
for ($i = 0; $i < 3; $i++) {
$currImg = getImage();
$_SESSION['img'][] = $currImg;
echo $currImg . '<br>';
}
?>
All displayed images are stored into SESSION variable. When all images are displayed, this SESSION var is reset and will start a new cycle.
I'm trying to build a simple auto suggest input bar that connects to a MySql database and retrieves data. The issue that I'm running into is that when I type in the name of an object that I know exists in the databse, the text bar doesn't return any results, instead it just provides me with an empty dropdown box.
The best I can tell, the issue has to do with the javascript that is used within the PHP portion of the code. Unfortunately, I can't seem to figure out why it's causing an issue.
<?php
mysql_connect("host", "user", "passsword") OR DIE ('Unable to connect to database! Please try again later.');
mysql_select_db('DBName');
$query = 'SELECT Device_type FROM Device';
$result = mysql_query($query);
$counter = 0;
echo"<script type='text/javascript'>";
echo"this.nameArray = new Array()";
if($result) {
while($row = mysql_fetch_array($result)) {
echo("this.nameArray" .$row ['Device_type'] . "';");
$counter += 1;
}
}
echo("</script>");
?>
When I take out the echo"<script type='text/javascript'>"; and echo"this.nameArray = new Array()"; then It displays the Device_type content on the top of the page when the page is loaded. This obviously isn't what I want, but it does prove that the database connection is at least set up correctly. Since this chunk of PHP is referring to some javascript, I will also prove the function in which it's referring to.
function doSuggestions(text) {
var input = text;
//window.alert(text);
var inputLength = input.toString().length;
var code = "";
var counter = 0;
while(counter < this.nameArray.length) {
var x = this.nameArray[counter]; // avoids retyping this code a bunch of times
if(x.substr(0, inputLength).toLowerCase() == input.toLowerCase()) {
code += "<div id='" + x + "'onmouseover='changeBG(this.id);' onMouseOut='changeBG(this.id);' onclick='doSelection(this.innerHTML)'>" + x + "</div>";
}
counter += 1;
}
if(code == "") {
outClick();
}
document.getElementById('divSuggestions').innerHTML = code;
document.getElementById('divSuggestions').style.overflow='auto';
}
Any suggestions as to why the suggestion box isn't providing suggestions when I start typing? If I type A into the text box, the suggestion box should appear showing me all items in the database that start with A.
there are some errors in your js strings
`echo"var nameArray = new Array()";`
`echo("nameArray.push('" .$row ['Device_type'] . "');");`
that way you'll push device types into the nameArray var.