I'm having a strange issue where using the % operator isn't grabbing the right database entries for my autocomplete bar.
Here is a sample of my database structure:
Here is what happens when I search the letter 'g' in my search bar. Note that I have the query echoed at the bottom of the div so you can see the correct thing is being searched:
Then here is what happens when I add an 'a' after the g. You would expect the entry to remain there, as the entry's name is "aattaagataca", and it contains a ga, flanked by some other characters.
On another note, the search of the letter 'g' didn't return the '5gooper' entry. Any ideas as to why this might be happening? I will post my sample code, but please don't making comments about sql security cause I'm just coding the raw stuff for now. Also don't redirect me to jQuery UI's autocomplete because I'm not looking to use that.
PHP
$searchquery = $_POST['searchquery'];
$searchquery2 = "%$searchquery%";
$query = "SELECT id, name, author, date FROM data WHERE name LIKE '$searchquery2' ORDER BY DATE DESC LIMIT 20";
$result = mysqli_query($con, $query);
$row = mysqli_fetch_array($result);
while ($row = $result->fetch_assoc()) {
echo "<a href=\"preview.php?id=$row[id]\"><div class=\"searchResult\">";
echo $row["name"];
echo "<br/>";
echo "<b>Author: </b>";
echo $row["author"];
echo "<br/>";
echo "<b>Date: </b>";
echo $row["date"];
echo "</div></a>";
echo "<hr>";
}
print_r ($row);
echo "$searchquery2";
JS/jQUERY
$('#sbar').keyup(function(){
var query = $(this).val();
$.ajax
({
url: "autocomplete.php",
data: {searchquery: query},
type: 'POST',
success: function(data){
$('#acd').html(data); //acd stands for auto complete div
}
});
});
Basically my query is just very inconsistent with what it returns. When I query my SQL database directly (through phpMyAdmin, it indeed returns the correct entries. For example, a query such as:
"SELECT * FROM data WHERE name LIKE '%g%' ORDER BY DATE DESC LIMIT 20"
Returns both entries which contain 'g' (gooper and gataca).
*****EDIT*****
Here is the result of typing 'g' and doing print_r ($row);
simply remove the following line
"$row = mysqli_fetch_array($result);" from your code and you should be fine. Your application has already retrieved the first record before entering the while-loop. That's why you only get a single record while searching for %g% and no record while searching for %ga%
Related
I wanna build a presence check for our choir in the style of tinder but not as complex.
The database contains names and file paths of pictures of the members. When you click on the "present" or "not present" button, the next picture and name should be shown. In the background, the database table should be updated with true/false for presence. (this will be done later)
My problem is that it almost works, but instead of showing one member, it shows all members with their pictures in one single page.
I understand that I could fire with Javascript to continue and paused php-function but I don't get the clue how.
I tried "break" in the php and call the function again but that didn't work.
<?php
$conn = new mysqli(myServer, myUser, myPass, myDbName);
$sql = "SELECT * FROM mitglieder";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<img class='pic' src='" .$row["folder"]. "/" .$row["img"]. "'><br>" ;
echo "<div id='name'>" .$row["vorname"]. " " .$row["name"]. "</div> <br>";
echo "<img src=''img.png' id='present' onclick='isPresent()'>";
}
} else {
echo "0 results";
}
$conn->close();
?>
<html>
<script>
$( document ).ready(function() {
console.log("Ready");
);
</html>`
You can use php function
mysqli_fetch_all()
assign it on the variable outside the while loop and loop or access the indexes in your code.
For Example:
$data = mysqli_fetch_all();
echo $data[0]['name'];
foreach($data as $item)
{
echo $item['name'];
}
You need a way to establish a "state" between your web page and the PHP backend so that you can step through the data. I suggest something like this:
Use an auto-increment integer primary key for the database. That way you can access the data in index order. Let's name the column id
Have your JS code send a form variable - named something like LAST_ID to the PHP in your get. i.e http://someurl.com/script.php?LAST_ID=0
On your first call to the server, send LAST_ID = 0
In your PHP code, fetch the value like this: $id = $_GET('LAST_ID');
Change your SQL query to use the value to fetch the next member like this:
$sql = sprintf("SELECT * FROM mitglieder where id > %d limit 1", $id); That will get the next member from the DB and return only 1 row (or nothing at the end of data).
Make sure to return the id as part of the form data back to the page and then set LAST_ID to that value on the next call.
You can use a HTTP POST with a form variable to the server call that sets that member id to present (maybe a different script or added to your same PHP script with a test for POST vs GET). I suggest a child table for that indexed on id and date.
I hope that puts you in a good direction. Good luck
I've written a PHP script that can populate a table in a particular way so that multiple events (or no events) can be put in one square in an HTML - similar to the layout a calendar would have. But, there's a problem, the while statement I created to fill in squares in the table when there is no data doesn't detect when there is data, and fills the entire table with empty squares. This is what the output looks like (The page is styled using Bootstrap 3). From the mysql data I have provided, these events should be in the square at {Period 1, Monday}.
Here is my data in a mysql database; mysql data
Here is a snippet of the part of the page related to this table;
<?php
$query = "SELECT * FROM configtimetabletwo WHERE term = ".$term." AND week = ".$week." ORDER BY period, day LIMIT 100;";
$results = mysqli_query($conn, $query);
$pp=1; //The current y value of the table
$pd=0; //The current x value of the table
echo '<tr><td>';
while($row = mysqli_fetch_row($results)) {
while((pd!=$row[3] or $pp!=$row[4]) and $pp<6){ //This while statement fills in empty squares and numbers each row.
if($pd==0) {
echo $pp."</td><td>";
$pd++;
}
elseif($pd<5){
echo "</td><td>";
$pd++;
}
else {
echo "</td></tr><tr><td>";
$pd=0;
$pp++;
}
}
echo '<a href="?edit='.$row[0].'" class="label label-default">';
echo $row[5].' '.$row[6].' - '.$row[7]."</a><br>";
}
echo "</td></tr></table>"
?>
I haven't been able to figure out why this happens so far, thanks in advance to anyone who has any idea what's going on.
In the comments below my question, pavlovich pointed out the error. In this case, it was simply an issue of forgetting to use a $ to reference a variable. It would seem that this doesn't throw an error in a while statement like it would elsewhere.
I am trying to make a leaderboard and sort my data by kills, but when I try to make it so it only grabs name, kill, death it doesnt grab anything but when I have it grab it all it works. Anyone know why? Code is below please assist.
<?php
$query = $koneksi->prepare("SELECT * from `player`");
$query->execute();
if($query->rowCount() == 0)
I am grabbing my mysql data here, if I change the * to the data I need no data is displayed.
echo "<tr><td colspan='6'><small>There's no player on ban list</small></td></tr>";
}
while($data = $query->fetch())
{
echo "<tr><td>".$data['name']."</td>";
echo "<td>".$data['kill']."</td>";
echo "<td>".$data['death']."</td>";
$kd = $data['kill'] / $data['death'];
echo "<td>".$kd."</td></tr>";
}
?>
Is it something to do with this or is something wrong? I am really confused.
Here you have to use bind_result() and in that you have to pass the number of parameters which is equal to your number of field from your player table.
Because here you are fetching data using select * query.
Hi I have created a drop down combo box on a form using a mysql query of 3 tables and this is working fine, now I want to perform another query on the datasabase when I select an item in the drop down combo with this running a query on the database and returning the values required to populate the form with additional data in defined fields.
below is how far I have got to date....
$query3 = "SELECT customers.id, customers.email, customers_customfields.customer_id, customers_customfields.field_value, orders.sign_date, orders.sub_id, orders.domain_name, orders.cust_status
FROM customers, customers_customfields, customers_orders, orders
WHERE customers_orders.order_id = orders.sub_id
AND customers.id = customers_orders.customer_id
AND customers.id = customers_customfields.customer_id
AND customers_customfields.field_id = 1";
$result = mysql_query ($query3);
echo "<select name=orders value='Select from the list provided '>";
while($drop=mysql_fetch_array($result)){
//data stored in $drop
echo "<option value=$drop[id]>$drop[sub_id] $drop[id] $drop[field_value] $drop[sign_date] $drop[domain_name] $drop[cust_status]</option>";
}
echo "</select>";
PHP is strictly a server-side language. If you want to have fields from a database dynamically update the application for the user (without having to submit and refresh), you're going to have to use AJAX.
Read through some AJAX tutorials to get the general idea.
Also, it would be a good idea to use a database abstract layer such as PDO.
It's helpful in almost any context, allowing for the use of prepared statements, as well as other goodies. Also, use MySqli in place of MySql, which is deprecated.
Ajax tutorials: http://www.smashingmagazine.com/2008/10/16/50-excellent-ajax-tutorials/
PDO: http://php.net/manual/en/book.pdo.php
Prepared statements: http://php.net/manual/en/pdo.prepared-statements.php
MySqli: http://php.net/manual/en/book.mysqli.php
You should indeed work with AJAX and PHP.
For example, first set a jQuery.change trigger on your dropdown doing like this:
$(document).ready(function () {
$('#yourDropDown').change(function (e) {
yourFunction($(this).val());
});
});
function yourFunction(inputString) {
$.ajax({
url: "../folder/yourPHP.php",
//The inputString will contain the value of your DropDown, you will give this parameter in the querystring
data: 'queryString=' + inputString,
success: function (msg) {
//MSG will be the "message" from the query
//As you see you'll put the MSG in your HTML of your #yourFormTag
//This message can contain everything you want
if (msg.length > 0) {
$('#yourFormTag').html(msg);
}
}
});
}
Just AN Example of A .PHP file:
<?php
if (isset($_REQUEST['queryString'])) {
include '../yourConnection.php';
$inputString = $_GET['queryString'];
$select_query = "SELECT <yourColumns>
FROM <yourTable>
WHERE <Where you want to check if inputString is the same> LIKE CONCAT('%', :inputString, '%')
ORDER BY <order if you want? ASC";
$get = $db->prepare($select_query);
$get->execute(array(':inputString' => $inputString);
//For example to fill a select
echo '<select>';
while ($row = $get->fetch(PDO::FETCH_ASSOC)) {
echo "<option value='" . $row['yourColumn'] . "'>" . $row['yourColumn'] . "</option>";
}
echo '</select>';
}
?>
As I said the .PHP file is an example.
Hope this helps, Cheers!
I am trying to show the results of the status of a bidding item using jQuery every second on every row in MySQL table, however only the result of the last row of the table is returned.
<?php
$query = "SELECT item, description, price, imageData, status, username, item_id FROM items";
$result = mysql_query($query) or die(mysql_error());
$z=0;
while($row = mysql_fetch_array($result))
{
//echo other columns here//
echo "<td><div id=status$z></div></td>";
?>
<script type=text/javascript>
function updatestatus(itemnum)
{
var url="updatestatus.php?auc=<?php echo $row['item_id']; ?>";
jQuery('#status' + itemnum).load(url);
}
setInterval("updatestatus(<? echo $z?>)", 1000);
</script>
<?
$z++;
}
?>
When I view source in the browser, the values for #status and auc for every row are correct. What am I missing here?
Here's the code for updatestatus.php
<?php
session_start();
require_once("connect.php");
$id = $_GET['auc'];
$getstatus = mysql_query("SELECT status FROM items WHERE item_id = '$id' ");
$row = mysql_fetch_array($getstatus);
echo"$row[status]";
?>
Everything looks good, save for the fact that it looks like you're creating multiple references to your updatestatus() function.
In Javascript, if you create multiple functions with the same name, calling them will only result in one of them running, usually the first or last one (depending on the implementation), so all the code you need to run in those functions needs to sit together in one function body.
If you're determined to use the code you've created, you'd need to throw all those update calls into one function body. There would be better ways to achieve what you need, but doing it with the code you've created, this would probably work better:
<?php
$query = "SELECT item, description, price, imageData, status, username, item_id FROM items";
$result = mysql_query($query) or die(mysql_error());
$javascript = "";
$z=0;
while($row = mysql_fetch_array($result))
{
//echo other columns here//
echo "<td><div id=status$z></div></td>";
// build the javascript to be put in the function later over here...
$javascript .= "jQuery('#status". $z ."').load('updatestatus.php?auc=". $row['item_id'] ."');";
$z++;
}
?>
...and then further down the page, create the javascript (modified slightly):
<script type=text/javascript>
function updatestatus()
{
<?php echo $javascript; ?>
}
setInterval(updatestatus, 1000);
</script>
So you're basically building up the Javascript that you'll need in your function, echoing it out inside the function body, and then setting the interval will call all that code, in this case, every second.
Like I said, there are definitely more efficient ways to achieve what you're trying to do, but this should work fine for now. I hope this makes sense, but please let me know if you need any clarity on anything! :)
I don't see that you're populating data using a incrementor. Is this supposed to be adding content to a page or replacing the content? from what it looks like it will just display one item, and then replace that one item with the next until it's done, which is why you see only the last row.
OR ...
the jquery update isn't being fed the $i variable .. change the function to
function updatestatus(itemnum) {
and then jquery echo to jQuery('#status' + itemnum).load(url);
then you can add the on-click/ or whatever to include the number
onclick='updatestatus("1")'
on the other hand you might be needing to pass the total number of items to the function and then creating an if there to cycle through them (not tested, but you get the idea i hope)
function updatestatus(numitems) {
var url = "";
var itemID = "";
for (i = 1; i <= numitems; i++) {
itemid = getElementById('#status'+numitems).getAttribute("itemID")
url="updatestatus.php?auc="+itemID;
jQuery('#status'+numitems).load(url);
}
}
setInterval("updatestatus()", 1000);
and the html element for "#status1" as created by the PHP should look like this:
<div id="status1" itemid="23455">
</div>