I have this code:
$result = mysql_query("SELECT * FROM quote ORDER BY RAND() LIMIT 1") or die(mysql_error());
$row = mysql_fetch_array( $result );
echo $row['frase'];
It echo´s a random "frase" every time you query.
What I want to do is avoid having the same result in consecutive queries.
To make myself clear, if in my database I´ve got:
1 a
2 b
3 c
If from echo $row['frase']; I got a the the next result can´t be a.
I hope I made myself clear and if not please comment and I´ll expand!
Thanks in advance!
BTW: sorry to #deceze #zerkms #Dr.Molle because last question was a total mess! No harm ment, just a noob on a spree :)
EDIT:
To answer Jason McCreary I actually call it like this:
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax_info.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
Since this last query needs to persist across page refreshes, you need to use a session. Something along these lines:
session_start();
if (empty($_SESSION['lastresult'])) {
$_SESSION['lastresult'] = null;
}
$query = "SELECT * FROM `quote` WHERE `id` != '%s' ORDER BY RAND() LIMIT 1";
$query = sprintf($query, mysql_real_escape_string($_SESSION['lastresult']));
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result);
$_SESSION['lastresult'] = $row['id'];
echo $row['frase'];
You may want to store the last x results in the session and use NOT IN () in your query to avoid every second (third, forth, ...) quote being the same.
Related
I am creating a php search. I select the 2 menus result from the database. The first menu works fine, but the second one no. Can you please help me?
This is my home.php
<?php
require("ConfigPage.php");
$sql="SELECT LocationName
FROM tblplacelocation
Join tblplace ON tblplace.PlaceID=tblplacelocation.PlaceID
Join tbllocation ON tbllocation.LocationID=tblplacelocation.LocationID
where PlaceType='Hotels'" ;
$result = mysql_query($sql,$con);
echo '<form><P style="color:white;">Region</P>
<select name="PlaceID" onchange="showUser(this.value)">
<option value="">Region:</option>';
while($data = mysql_fetch_array($result))
{
$id= $data['PlaceID'];
$lname = $data['LocationName'];
echo "<option value='". $lname. "'>".$lname."</option>";
}
echo "</select></form>";
echo "<div id='txtHint'></div>";
echo "<div id='divImage'></div>";?>
this is the getuser.php
<?php
$q = intval($_GET['q']);
include("ConfigPage.php");
$sql="SELECT PlaceName
FROM tblplacelocation
Join tblplace ON tblplace.PlaceID=tblplacelocation.PlaceID
Join tbllocation ON tbllocation.LocationID=tblplacelocation.LocationID
WHERE LocationName = '".$q."' AND PlaceType='Hotels'";
$result = mysql_query($sql,$con);
echo '<form><P style="color:white;">Place Name</P>
<select name="adminID" onchange="showImages(this.value)">
<option value="">Select a place:</option>';
while($data = mysql_fetch_array($result))
{
$pid= $data['LocationName'];
$pname = $data['PlaceName'];
echo "<option value='". $pid. "'>".$pname."</option>";
}
echo "</select></form>";
mysql_close($con);
?>
and this is the java script:
function showUser(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
I don't know what's wrong. The first menu displays the result but the second menu contains nothing.
I would suggest you to use Firebug for debugging.
check if you have any javascript errors (maybe syntax error)
check if your ajax request is being send, if yes, check what's inside the response
check if your dom element is being selected correctly ... in firebug you can execute javascript in the console area. check if your document.getElementById selects the correct element by inserting something yourself
if all of this works, check if your select element has empty options. if this is the case, your variables should be empty
if your select element has no options, something with your sql select may be wrong
If you're just experimenting, it's ok, but otherwise let me say that your code looks pretty ugly. This is not the way you should programm things.
You should think about dividing your code by concerns. Check out the Model-View-Controller Pattern and beginner tutorials for any PHP-Framework.
MVC:
http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller
A Framework which is easy to learn:
http://www.yiiframework.com/
i have this code below of javascript:
<script>
function showUser(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","includes/get_user.php?q="+str,true);
xmlhttp.send();
}
</script>
and the php sql script is given below:
<?php
$testQrys = "SELECT * FROM test where status = 1";
$testdbResults = mysql_query($testQrys);
?>
<select size='5' width='925' style='width: 925px' name='users' onchange='showUser(this.value)' multiple>
<?php while($test = mysql_fetch_array($testdbResults )) { ?>
<option class='h4' value='<?php print($test[9]); ?>'>
<?php print($test[5]);echo" ( ";print($test[9]);echo" )"; ?>
</option>
<?php } ?>
</select>
<div id="txtHint"></div>
and the get_user.php code is:
<?php
$q=$_GET["q"];
$con = mysqli_connect('localhost','root','','airways');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM test WHERE m_email = '".$q."'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
echo "<input type='text' name='staff_no[]' value='".$row['m_staff_no']."'>";
}
mysqli_close($con);
?>
now what i want is when i select one user in the select option it shows the staff no of that user but when i select multiple users it does not show the staff no of other users i select.
please help me with the change in code so i can get the staff no of users like (22344, 44333, 33344, 55443, 11125, 25263) in the text box
waiting for the kind and prompt responses.
Thanks in advance
The error is coming from showUser(this.value). This returns only the first selected element's value. You need to cycle through all options and concatenate them together to make a string that you will be able to send as a parameter.
Change your javascript code to something along those lines. Note that you will need to change your PHP code in order to separate the emails, sanitize them and create a working WHERE m_email IN () query.
You will need to add id="users" to your HTML code first.
var usersList = document.getElementById('users');
var emailString = '';
for (user_counter = 0; user_counter < usersList.options.length; user_counter++) {
if (usersList.options[user_counter].selected) {
emailString += usersList.options[user_counter].value;
}
}
Then send emailString as the parameter to the PHP script. Test it again with log.txt in case you get an error.
I have a simple (or so I thought) PHP, MYSQL, AXAX system set up to register votes for items on my website. I'm only doing upVotes so there's only one button.
My issue is that when the page loads, the correct number of votes for the item is displayed, but upon the first click of the upVote button, the value does not change. I know I must be missing something, but I have no idea what. It's probably simple... but I just can't figure it out.
Everything connects to the DB just fine. That's why I left all that code out.
Any help is greatly appreciated.
This is the javascript I have:
<script type="text/javascript">
function voteButton(str)
{
if (str=="")
{
document.getElementById("voteUp").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("voteUp").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","vote?id="+str,true);
xmlhttp.send();
}
</script>
This is the php file used to query the database:
<?php
$id=$_GET["id"];
include("myDatabaseStuff.php");
include("global.php");
$result = mysql_query("UPDATE TABLE SET up_mod = up_mod + 1 WHERE img_id = $id");
if (!$result) {
die('Invalid query: ' . mysql_error());
}
while($row = mysql_fetch_array($getUpVoteResult))
{
echo $row['up_mod'];
}
?>
This is the HTML I use on the page to display the values/button:
<div class="span1" style="margin:30px 0 0 10px;">
<button onclick="voteButton('<?php echo $id;?>')" class="btn btn-large" type="button" style="margin-top:5px"><div id="voteUp"><?php echo $votes[0] ?></div><i class="icon-thumbs-up"></i></button>
</div>
Add:
$getUpVoteResult = mysql_query("SELECT up_mod FROM table WHERE img_id = $id") or die ("Invalid query: " . mysql_error());
before the while loop.
You also don't need a while loop, since there's just one row.
After your update, please do the separate SELECT.
I made a search bar, for searching users in my database, and I will share my code below. But one problem is that, if I have 5 users in a table, it shows these 5 users, but if I have 1,000 than it shows all 1,000.
Whatever I tried to limit it, it did not work. Sometimes it completely kills the PHP script.
Does anyone know how to solve that and limit to only 5 results displayed per search query from the code below?
HTML INPUT AND AJAX SCRIPT:
<input id="text" type="text" name="text" onkeyup="showHint(this.value)" autocomplete="off" />
<div id="inner" class="inner"></div>
<script>
function showHint(str) {
if (str.length==0) {
document.getElementById("inner").innerHTML="You haven't search. Please have :D";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("inner").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("REQUEST","searchquery.php?text="+str,true);
xmlhttp.send();
}
</script>
AND searchquery.php:
<?
$text = $_REQUEST['text'];
$text = preg_replace('#[^a-z0-9]#i', '', $text);
function connect($database) {
mysql_connect('localhost','root','');
mysql_select_db($database);
}
connect('developing');
$query = "SELECT * FROM users WHERE first_name LIKE '%$text%' OR last_name LIKE '%$text%'";
$action = mysql_query($query);
$result = mysql_num_rows($action);
if ($result == 0) {
$output = "User does not exist...";
}else{
while ($row = mysql_fetch_array($action)) {
$output .= '<div class="output"><img src="/'.$row['avatar'].'"><a href="#">'.$row['first_name'].' '.$row['last_name'].'</div><br />';
}
}
echo $output;
?>
Can anybody see some solution on how to make that limit?
Use LIMIT in your query:
SELECT *
FROM users
WHERE first_name LIKE '%$text%'
OR last_name LIKE '%$text%
LIMIT 5'
Can you find the problem? It doesnt insert it into the database but I get no error.
Im a total ajax noob yes, I found this code and modified it a bit and i think it should work but it dont
rate.php
$v = $_GET['v'];
$conn = mysql_connect('***', '***', '***');
$db_selected = mysql_select_db('***', $conn);
$sql="INSERT INTO votes (title_id, score) VALUES (1, $v)";
$result = mysql_query($sql) or die(mysql_error());
echo "Vote has been added.";
?>
title.php
<script type="text/javascript">
function addVote(str)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","include/ajax/rate.php?v="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
Rate: 1 2 3 4 5
Can't see anything wrong (as far as logic is concerned). So here is a vague debug answer:
First you should simply call your php script directly to see if and what it outputs:
http://localhost/thingy/include/ajax/rate.php?v=3
If that works, then the problem is your Javascript code. Try with jQuery just to be sure:
function addVote(n) {
$('#txtHint').load("rate.php?v=" + n);
}
Add a timestamp to avoid caching:
xmlhttp.open("GET","include/ajax/rate.php?t="+new Date().getTime()+"&v="+str,true);
validation of the input:
$v = filter_input(INPUT_GET,
'v',
FILTER_VALIDATE_INT,
array(
'flags' => FILTER_NULL_ON_FAILURE,
'options' => array('min_range' => 1, 'max_range' => 5)
));
if(!$v){exit();}
Try put single quote in the query string's values:
$sql="INSERT INTO votes (title_id, score) VALUES ('1', '" . mysql_real_escape_string ($v) . "')";
and use
mysql_real_escape_string (string $unescaped_string [, resource $link_identifier ]);
on the variable to inject