I'm currently trying to learn HTML, AJAX, PHP, and MYSQL. I'm currently building a webapp just for internal use. It al seemed to work but now I'm experiencing some lag in my code using the MYSQL function.
Here's what happens:
First off all, I create some "profile images" form an sql database. trough PHP like this:
<?php
$price = 30;
$con = mysql_connect('localhost', 'root', 'root');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("Og297", $con);
$result = mysql_query("SELECT * FROM Og297.Drinkers");
while($row = mysql_fetch_array($result))
{
$picture = $row['Picture'];
$name = $row['Name'];
$nameup= $name."up";
$namep= $name."p";
$Onbetaaldresult = mysql_query("SELECT COUNT(Betaald) AS ob FROM Og297.Bierlijst
WHERE Betaald='1' AND Name='$name'");
$Onbetaaldarray= mysql_fetch_array($Onbetaaldresult);
$Onbetaald= $Onbetaaldarray['ob'];
$Betaaldresult = mysql_query("SELECT COUNT(Betaald) AS b FROM Og297.Bierlijst
WHERE Betaald='0' AND Name='$name'");
$Betaaldarray= mysql_fetch_array($Betaaldresult);
$Betaald= $Betaaldarray['b'];
echo "<div onclick=\"addBeer('$name','$price');\" class= 'thumbnail'><img src= $picture height= '90' width= '90' alt= $name title= $name><div class= 'overlay'><span id=$nameup class='unpaid'>$Onbetaald</span><span id= $namep class='paid'>/$Betaald</span></div></div>";
}
mysql_close($con);
?>
So this shows for every user a picture div, on top of that it shows to span's with the ID's Paid and Unpaid(The app is for keeping track how much beer we've paid and how much still need to be paid). This all works :)
next I have some functions;
On is addBeer, wich ads a beer into a table, including the name of that person. This is done trough Ajax.
function addBeer (n,p)
{
$.post("AddBeer.php",{naam: n, price: p});
updateBeer(n);
}
So after having inserted the beer into the datbase, I want it to update the Paid and Unpaid span's. I do this by using updateBeer.
function updateBeer (n)
{
$.post("UpdateBeer.php",{naam: n},function(data) {
changeInfo(n,data.betaald,data.onbetaald);
},"json");
}
This returns the amount of paid and unpaid in a Json object. Those values(including the name of the person are then given to changeInfo function, wich will update the span's like this:
function changeInfo(n,b,ob)
{
window.alert("ja");
document.getElementById(n + "up").innerHTML=ob;
document.getElementById(n + "p").innerHTML="/" + b;
}
However, the info is not updated every time I click an image.. It lags behind, the beers are inserted tough, but the updating of the span's is just not happening. How come?
Thanks very much for even reading this huge question!
The problem in my code was that the AJAX request where async. Thus causing problems when the rest of the script was executed before the AJAX request was completed. The trick was to set the AJAX request to set Async to false!
Thanks!
Related
I'm making a website. and one of the features i want it to have is to have a simple game that connects 2 players together. my problem is I don't know how to make it so both player are in the same "room" because on room holds only 2 players.
On way i approached this is once one player joined, he gets a "wait for next player" message and waits while sending to the database that one player have joined. how do i make it keep checking for the next 3 minutes if the next player joined?
UPDATE
First here is the code so far:
<html>
<title>SiteName (test)</title>
<head>
<?php
$servername = "localhost";
$u
sername =
$password =
$dbname =
try
{
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT * FROM game');
$stmt->execute(array('gameID' => $gameID));
while($row = $stmt->fetch()) {
print_r($row);
echo "<br />\n";
}
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
?>
<button onclick="myFunction()" id="w">Look for Game</button><br>
<script>
function myFunction() {
var elem = document.getElementById("w").innerHTML = "Wait";
var counter = 10;
var label= document.getElementById("lbl");
var counter = 10;
var clabel= document.createElement("p");
clabel.innerHTML = "You can download the file in 10 seconds.";
var id;
label.parentNode.replaceChild(clabel, label);
id = setInterval(function() {
counter--;
if(counter < 0) {
clabel.parentNode.replaceChild(label, clabel);
clearInterval(id);
} else {
clabel.innerHTML = "You can download the file in " + counter.toString() + " seconds.";
}
}, 1000);
}
</script>
<?php
$conn = null;
?>
</body>
</html>
Am trying to make it so that if the first player joined, he will be waiting (i have it for 10 seconds here as a test) until the other joins. the way am trying to do it is to have a field in the database will know if the a player is in that page and await the next player. I read something about long polling but not sure how to implement it for my case.
Any feed back would be helpful, Thank you
PHP is not the best language to do this in, but if you still want to do it.
Look into using Ratchet (http://socketo.me/), which is a PHP websocket library. A websocket is full duplex, meaning that a connection between the server and client is kept open. Game state and player actions can then be communicated through this.
http://socketo.me/docs/hello-world is an example you can learn from.
first you will want javascript or some client side code to handle this. as php will execute on the server side then display to the user. if you use ajax with javascript you can get the client side and server side to work together.
you will want to use a while loop, in this loop you will set a timeout.
in the while loop you can call the ajax script you want untill you get your result you want. I'm assuming you plan on making this a turn by turn game for the players. you will want a table that sets "true" to if player 1 or player 2 are in the game. if both are turn then the game begins.
Hope this logic helps
I want to use one single page with pre-defined divs, layout etc. as basis so that when a product is clicked on from elsewhere it loads that product info onto the page?
They way im doing it ill be sitting here till about 2020 still typing out product info onto pages.
EDIT*************
function product ()
{
$get = mysql_query ("SELECT id, name, description, price, imgcover FROM products WHERE size ='11'");
if (mysql_num_rows($get) == FALSE)
{
echo " There are no products to be displayed!";
}
else
{
while ($get_row = mysql_fetch_assoc($get))
{
echo "<div id='productbox'><a href=product1.php>".$get_row['name'].'<br />
'.$get_row['price']. '<br />
' .$get_row['description']. '<br />
' .$get_row['imgcover']. "</a></div>" ;
}
}
}
In addition one problem I have with that code is that the <a href> tag only goes to product1.php. Any ideas how I can make that link to blank product layout page that would be filled with the product info that the user has just clicked on, basically linking to itself on a blank layout page.
Thanks any help would be great!
Thanks Maxyy
Since you dont have code this is a general way of doing this. What you want is a template for the product page
Query the database
load the data into a variable
make a script that will print out the data from the variable into a product page
somescript.php
<?php
$productid = $_REQUEST['productid']; //Of course do sanitation
//before using get,post variables
//though you should be using mysqli_* functions as mysql_* are depreciated
$result = mysql_query("select * from sometable where id='{$productid}");
$product = mysql_fetch_object($result);
include("productpage.php");
productpage.php
<div class="Product">
<div class="picture"><img src="<?php echo $product->imghref;?>" /></div>
<div class="price"><?php echo $product->price;?></div>
</div>
so on and so fourth. Included scripts use whatever variables are currently in the scope of the calling function
If you are meaning to load the products into the same page without doing another page load you will need to use ajax. Which is javascript code that use XHR requests to return data from a server. You can either do pure javascript or a library like jQuery to simplify the process of doing a xhr request by using $.ajax calls.
I know this question has been asked over 4 years ago, but since there's been no answer marked as right, I thought I might chip in.
First, let's upgrade from mysql and use mysqli - my personal favorite, you can also use PDO. Have you tried using $_GET to pull the id of whatever product you want to see and then displaying them all together or one at a time?
It could look something like this:
<?php // start by creating $mysqli connection
$host = "localhost";
$user = "username";
$pass = "password";
$db_name = "database";
$mysqli = new mysqli($host, $user, $pass, $db_name);
if($mysqli->connect_error)
{
die("Having some trouble pulling data");
exit();
}
Assuming the connection was made successfully we move on to checking for an ID being set. In this case I check it via an URL param assumed to be id. You can make it more complex, or take a different approach here.
if(isset($_GET['id']))
{
$id = htmlentities($_GET['id']);
$query = "SELECT * FROM table WHERE id = " . $id;
}
else
{
// if no ID is set, just bring all the results down
// then you can modify how, and which table the results
// are being used.
$query = "SELECT * FROM table ORDER BY id"; // the query can be changed to whatever you would be prefer
}
Once we have decided on a query we go on to start querying the database for information. I have three steps:
Check query >
Check table for records >
Loop through roles and create an object for each.
if($result = $mysqli->query($query))
{
if($result->num_rows > 0)
{
while ($row = $result->fetch_object())
{
// you can set up your element here
// you can set it up in whatever way you want
// to see your product being displayed, by simply
// using $row->column_name
// each column becomes an object here. So your id
// column would be pulled using $row->id
echo "<h1>" . $row->name . "</h1>";
echo "<p>" . $row->description . "</p>";
echo "<img src=" . $row->image_path . ">";
// etc ...
}
}
else
{
// if no records match the selected ID
echo "Nothing to see here...";
}
}
else
{
// if there's a problem with the query
echo "A slight problem with your query.";
}
$mysqli->close(); // close connection for safety
?>
I hope this answers your question and can help you if you are still stuck on this problem. This is the bare skeleton of what you can do with MySQLi and PHP, you could always use some Ajax to make the page more interactive, and user-friendly.
Adding content to a page on click needs to be done in either Javascript or in JQuery.
You can use ajax call to retrive the needed data from php page, Syntax is here.
Or you can also load a php page to a div content with .load() function in JQuery, Syntax is here.
Is it possible to refresh a divs content only if new content is added to the database?
I'm using this for "recent posts" that appear in the side menu.
Right now the div is set refresh every 10 seconds.
Is it somehow possible to check it a new post was added to the db and then add only that posts data to the div?
I'm using MySql, php and jquery to do all of this.
Yes, you can do it by comparing the text content.
function updateHtmlContent() {
var htmlContent=$('#divToUpdate').text();
$.ajax({
type: "GET",
datatype: "text",
//php function that should give you the text back
url: 'dataBaseFunction.php',
success: function(data) {
if (htmlContent != data) {
$('#divToUpdate').text(data);
}
}
});
}
//compare and upate every 20 seconds
setInterval(updateHtmlContent(), 20000);
Hope this help!
YES IT IS POSSIBLE
The below code will get the recent photos that has been added:
AFTER THE TIMER.PHP WAS LAODED (or your wordpress blog page)
AND ONLY AFTER A NEW PHOTO IS ADDED (you can use it for recent posts, comments, or anything)
This can be used to create a live blog for example, where the user will see all the recent comments, images or posts, or everything, even if he doesn't reload the current page. And it won't consume a lot of bandwidth as the content will be reloaded ONLY IF THERE IS NEW ADDED (it will only send a tiny check in the database otherwise).
I've just finished working out a solution for that, and I have to share it with you. I was doing it for Wordpress, i needed a function that gets the photos that has been added ONLY after the user loaded the page. It could be done by simply refreshing the div every 5 seconds, but imagine if there were 20 photos, and they had to be refreshed every 5 seconds... that's a lot of MB of data. So we will refresh them ONLY when a new photo is added (you can apply it to anything, from posts to comments or users, etc.).
There are 3 PHP files: timer.php, check.php and display.php.
The timer.php will load the check.php every 5 seconds, to check if new content is added. Notice the -6 extraction from the time of the current load of check.php.
The date-time of the timer.php will be passed (by check.php?tim=**print date) through the check.php (by **display.php?timm='. $tizz .') and to the display.php, so we can use it for a reference in our database (that will be the time from where we will load all the images, if new images are added).
If any questions, just ask. It has to work for you too, as it works for me.
ENJOY! :)
Below are the 3 PHP files, just customize them for your needs:
THE TIMER.PHP (or your wordpress blog pages):
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
setInterval(function(){
$("#quotex a").load("check.php?tim=<?php print date("Y-m-d H:i:s"); ?>");
}, 5000);
});
</script>
<div id="quote"><a></a></div>
<div id="quotex"><a></a></div>
THE CHECK.PHP :
<?php
// Connects to your Database
mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("database name") or die(mysql_error());
// SQL query
$strSQL = "SELECT * FROM wp_posts WHERE post_mime_type LIKE 'image/jpeg' ORDER BY `wp_posts`.`id` DESC LIMIT 1";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysql_fetch_array
while($row = mysql_fetch_array($rs)) {
$atime = $row['post_date'];
$tizz = $_GET['tim'];
$dsff = $row['post_date'];;
$duff = date("Y-m-d H:i:s");
//convert the date-time into seconds so we can extract 6 seconds from it
$six = strtotime(date("Y-m-d H:i:s"))-6;
//convert the latest image date-time too from database so we can compare it
$sox = strtotime("$dsff");
if ($six < $sox)
{
echo '<script type="text/javascript">$(document).ready( function(){ $("#quote a").load("display.php?timm='. $tizz .'"); } ); </script>';
}
}
// Close the database connection
mysql_close();
?>
THE DISPLAY.PHP:
<?php
$tipp = $_GET["timm"];
// Connects to your Database
mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("database name") or die(mysql_error());
// SQL query
$strSQL = "SELECT * FROM wp_posts WHERE post_mime_type LIKE 'image/jpeg' AND post_date > '$tipp' ORDER BY `wp_posts`.`id` DESC LIMIT 10";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysql_fetch_array
while($row = mysql_fetch_array($rs)) {
//guid is the column where the image url is located in the wordpress database table
$atime = $row['guid'];
echo "<img src='". $atime ."' /><br />";
}
// Close the database connection
mysql_close();
?>
Yes is possible, but you need to create a method in php and use Ajax to refresh your div.
If you update your question with code I can provide an example.
I think you are probably about 90% of the way there. I assume you are using jQuery to AJAX in the content every 10 seconds (PS That seems like a lot?)
I think you could solve your problem by making the backside function start with posts after the most recent that was found.
So if your query looks like this now:
SELECT a,b,c FROM foo
You should change it to
SELECT a,b,c FROM foo WHERE id > $last_found_id
You can store last_found_id in your Javascript and send it back when you call the function. If your result set is empty then you don't have to refresh the div.
This change will also probably require that you are pre/appending to the div instead of overwriting it completely.
look at the setInterval(function, time) in javascript to make a loop each "time" (in milliseconds),
and the function $.ajax() in jQuery to pass the information to the server..
also, you have to create the new content with .html() or .append()
Please could someone help im building my first website that pulls info from a MySQL table, so far ive successfully managed to connect to the database and pull the information i need.
my website is set up to display a single record from the table, which it is doing however i need some way of changing the URL for each record, so i can link pages to specific records. i have seen on websites like facebook everyones profile ends with a unique number. e.g. http://www.facebook.com/profile.php?id=793636552
Id like to base my ID on the primary key on my table e.g. location_id
ive included my php code so far,
<?php
require "connect.php";
$query = "select * from location limit 1";
$result = #mysql_query($query, $connection)
or die ("Unable to perform query<br>$query");
?>
<?php
while($row= mysql_fetch_array($result))
{
?>
<?php echo $row['image'] ?>
<?php
}
?>
Thanks
Use $_GET to retrieve things from the script's query (aka command line, in a way):
<?php
$id = (intval)$_GET['id']; // force this query parameter to be treated as an integer
$query = "SELECT * FROM location WHERE id={$id};";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result) == 0) {
echo 'nothing found';
} else {
$row = mysql_fetch_assoc($result);
echo $row['image'];
}
There are many things to consider if this is your first foray into MsSQL development.
SQL Injection
Someone might INSERT / DELETE, etc things via using your id from your url (be careful!, clean your input)
Leaking data
Someone might request id = 1234924 and you expected id = 12134 (so some sensitive data could be shown, etc;).
Use a light framework
If you haven't looked before, I would suggest something like a framework (CodeIgniter, or CakePHP), mysql calls, connections, validations are all boilerplate code (always have to do them). Best to save time and get into making your app rather than re-inventing the wheel.
Once you have selected the record from the database, you can redirect the user to a different url using the header() function. Example:
header('Location: http://yoursite.com/page.php?id=123');
You would need to create a link to the same (or a new page) with the URL as you desire, and then logic to check for the parameter to pull a certain image...
if you're listing all of them, you could:
echo "" . $row['name'] . ""
This would make the link.. now when they click it, in samepage.php you would want to look for it:
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
//query the db and pull that image..
}
What you are looking for is the query string or get variables. You can access a get variable through php with $_GET['name']. For example:
http://www.facebook.com/profile.php?id=793636552
everything after the ? is the query string. The name of the variable is id, so to access it through your php you would use $_GET['id']. You can build onto these this an & in between the variables. For example:
http://www.facebook.com/profile.php?id=793636552&photo=12345
And here we have $_GET['id'] and $_GET['photo'].
variables can be pulled out of URL's very easily:
www.site.com/index.php?id=12345
we can access the number after id with $_GET['id']
echo $_GET['id'];
outputs:
12345
so if you had a list of records (or images, in your case), you can link to them even easier:
$query = mysql_query(...);
$numrows = mysql_num_rows($query);
for ($num=0;$num<=$numrows;$num++) {
$array = mysql_fetch_array($query);
echo "<a href=\"./index.php?id=". $row['id'] ."\" />Image #". $row['id'] ."</a>";
}
that will display all of your records like so:
Image #1 (links to: http://www.site.com/index.php?id=1)
Image #2 (links to: http://www.site.com/index.php?id=2)
Image #3 (links to: http://www.site.com/index.php?id=3)
...
Okay, so this is my first project using PHP and MySQL and I thought a Facemash style site using HTML, PHP and MySQL would be good place to start.
Everything works correctly except calling the "updateHits" function as an image hyperlink doesn't behave as I'd expect.
I am confident that the MySQL database is functioning correctly and the pictures do display as expected. My research points towards the use of iFrames, jQuery or AJAX to update the "hits" field although I cannot understand how to apply them here.
I hope my code is readable and any advice would be greatly appreciated!
<html>
<body>
<?php
// Make a MySQL Connection
mysql_connect("localhost", "admin", "admin") or die(mysql_error());
mysql_select_db("facemash") or die(mysql_error());
// Select two random people
$personA = rand(1, 28);
$personB = rand(1, 28);
// Ensure that it is not the same person
if ($personB == $personA) {
$personB = rand(1, 28);
}
// Function to return path of photo
function photoPath ($person){
$query = mysql_query("SELECT photo FROM people WHERE id=$person");
$result = mysql_fetch_row($query);
$result = $result[0];
echo $result;
}
// Function to update the hits field
function updateHits($person){
$query = mysql_query("SELECT hits FROM people WHERE id=$person;");
$result = mysql_fetch_row($query);
$result = $result[0];
$result++;
mysql_query("UPDATE people SET hits = $result WHERE id=$person");
}
?>
<!--Image for personA-->
<img src="<?php photoPath($personA);?>"/>
<!--Image for personB-->
<a href="<?php updateHits($personB);?>"/><img src="<?php photoPath($personB);?>"/></a>
</body>
</html>
Thanks.
Erm, PHP does not work that way. ;)
PHP is serverside code, you're creating a link that points nowhere. To get the effect you want you'll need to make an AJAX call to the server to tell it to update the hits.