I have managed to get this code to work for an application -- http://twitter.github.io/typeahead.js/ but, the problem I have run into, is that I need to be able to re-load the data. I would rather not duplicate the code to do this, although it's an option, it seems kind of silly. I have inserted some PHP into my JavaScript to create an array for the dropdown list, and it works great. But if I stuff it into a function, and then try to call the function in the document open, it doesn't work (nothing appears to happen).
$(document).ready(function()
{
// call function when page loads(?)
getAwards();
}); // end document.ready ...
This is the PHP code, if I comment out the JavaScript function parts it runs and the typeahead code sees the value of the array. If I put it into the function, it doesn't execute despite being called above, and I have no data for the typeahead code ...
function getAwards(
{
// build array for use with typeahead:
<?php
$sql_statement = "select title from awards order by title desc limit 1";
$aw_result = mysqli_query( $connect, $sql_statement );
$aw_row = mysqli_fetch_array( $aw_result );
$last_award = $aw_row["title"];
// need to rewind table:
mysqli_data_seek( $aw_result, 0);
// start from the top:
$sql_statement = "select title from awards order by title";
$aw_result = mysqli_query( $connect, $sql_statement );
$count = 0;
$out = 'awards = [';
while ( $aw_row = mysqli_fetch_array( $aw_result ) )
{
// the quotes deal with forcing this to handle
// branch names with apostrophes in them ...
$count++;
$out .= '"'. $aw_row["title"] . '"';
if( $aw_row["title"] != $last_award )
{
$out .= ',';
}
}
$out .= ']';
echo $out . "\n";
?>
})
I need to be able to update the data, and reload the list while working on the form (I am working that out in my fuzzy brain, but anyway I'll get to that -- currently intend to click a button to update the list used by the typeahead, which is why I want a function ...)
Any suggestions are gratefully accepted. I am at a loss ...
Related
I am writing a new feature plugin for a website I develop and am stuck with how to go about implementing such feature. I'm trying to return an SQL query to an array that I can then pass to a function in either PHP or JavaScript, to perform a random option picker, and display the results to the user. I'm trying to perform the random picker by an on-click functionality.
So far, I have figured out how to successfully select my SQL query, return statements, and in JavaScript, work with a random option picker. However, I have not been able to find a good way to combine all these things together to produce my result.
I was wondering if anyone knew of a way to do this. Is it better to perform the entire program functionality in PHP or better to pass it to a JavaScript function and return results through the JS code?
Here are some examples of my code. Please assume that my query works. I do not need the display option in my code. It is implemented to check query results. I was hoping to hide the array in the real plugin from users and use the returned results for the on-click functionality attached to an HTML element.
<?php
function choices() {
$config = parse_ini_file(*database file*);
$con = mysqli_connect(*database information*);
if(!$con){
exit("Please try again later.");
}
$query = "SELECT * FROM *query*";
$result = #mysqli_query($con, $query);
$num = mysqli_num_rows($result);
if ($num > 0) {
echo "<p>There are currently $num restaurants.</p>\n";
echo '<table width="60%">
<thead>
<tr>
<th align="left">Restaurant Title: </th>
<th align="left">Link: </th>
</tr>
</thead>
<tbody>
';
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo '<tr><td align="left">' . $row['post_title'] . '</td><td align="left">' . $row['guid'] . '</td></tr>
';
}
echo '</tbody></table>';
mysqli_free_result($result);
}
else {
echo '<p class="error">The results could not be retrieved.</p>';
}
mysqli_close($con);
}
$foo = choices();
?>
My JS code.
var favorites = ["choice #1, choice #2, choice #3, choice #4"];
var favorite = favorites[Math.floor(Math.random() * favorites.length)];
Thank you very much for any input regarding this question! I understand this is a rather lengthy question and I do appreciate time took to help me understand it.
Why not just have your database return a single random result since that's all you need?
SELECT * FROM tbl ORDER BY RAND() LIMIT 1
Take a look at this post about getting random rows
Put the results of the query in a PHP array. Then use json_encode() to convert that to a Javascript array. Then the onclick functionality can display a random element of the array.
$array = array();
while ($row = mysqli_fetch_assoc($result)) {
$array[] = $row['post_title'];
}
?>
<script>
var favorites = <?php echo json_encode($array); ?>;
$("#button").click(function() {
var favorite = favorites[Math.floor(Math.random() * favorites.length)];
alert(favorite);
});
</script>
I'm trying to delete an entry in my database using the code below. The javascript function takes me to index.php?delpost= with the correct "adventureID" but when I check my database the row is still there. I've very recently started using PDO so I'm wondering if the execute() statement might be the issue. $dbh connect to my database at the top of the page and it is working as it prints every row from the table I'm trying to delete rows from. My goal is to successfully delete a row when I call the javascript function. The issue is - it doesn't.
<script language="JavaScript" type="text/javascript">
function delpost(adventureID, title)
{
if (confirm("Are you sure you want to delete '" + title + "'" + " '" + adventureID + "'"))
{
window.location.href = 'index.php?delpost=' + adventureID;
}
}
</script>
<?php
if(isset($_GET['delpost'])){
$stmt = $dbh->prepare("DELETE FROM adventure WHERE adventureID = :adventureID");
$stmt->execute(array(':adventureID' => $_GET['delpost']));
header('Location: index.php?action=deleted');
exit;
}
?>
<?php
if(isset($_GET['action'])){
echo '<h3>Post '.$_GET['action'].'.</h3>';
}
try {
foreach($dbh->query("SELECT adventureID, title, postDate FROM adventure ORDER BY adventureID DESC") as $row) {
echo '<tr>';
echo '<td>'.$row['title'].'</td>';
echo '<td>'.date('jS M Y', strtotime($row['postDate'])).'</td>';
?>
<td>
Delete
</td>
<?php
echo '</tr>';
}
} catch(PDOException $e) {
echo $e->getMessage();
}
?>
Probably you are facing problem with MYSQL SAFE UPDATES being ON. To avoid it and be able to finally delete rows, you can engage in the following tactics:
SET SQL_SAFE_UPDATES = 0;
--- YOUR DELETE STATEMENT ---
SET SQL_SAFE_UPDATES = 1;
To check if you have SQL_SAFE_UPDATES enabled you can do by running:
SHOW VARIABLES LIKE 'sql_safe_updates'
Try to replace this code :
$stmt = $dbh->prepare("DELETE FROM adventure WHERE adventureID = :adventureID");
$stmt->execute(array(':adventureID' => $_GET['delpost']));
By the following :
$stmt = $dbh->prepare("DELETE FROM adventure WHERE adventureID = :adventureID");
$stmt->bindParam('adventureID', $_GET['delpost']);
$stmt->execute();
Explanation :
You can either : Use ":variable" in your query, then pass variables by binding them with the "bindParam" function.
Or : Use "?" in your query, and then pass variables in the "execute" function.
Full example can be found here : http://php.net/manual/fr/pdostatement.execute.php#example-1050
I'm in the process of establishing a website which uses JQuery's auto complete to give users suggestions on pages. I store the page ID and title in a SQL database (connecting using PDO). At the moment, I've got the auto complete feature working, however, I am absolutely stumped on how to get the auto complete list to turn into clickable links which direct the user to the relevant page based off the page ID in the database.
Here's my search.php file
<?php
require('includes/connect.class.php');
if (isset($_GET['term'])) {
$return_arr = array();
try {
$stmt = $conn->prepare('SELECT id, locationName FROM locations WHERE locationsName LIKE :term');
$stmt->execute(array(
'term' => '%' . $_GET['term'] . '%'
));
while ($row = $stmt->fetch()) {
$return_arr[] = $row['locationName'];
}
}
catch (PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
echo json_encode($return_arr);
}
?>
and my JavaScript
$(function() {
$(".locationlist").autocomplete({
source: "search.php",
minLength: 1
});
});
The database looks like this
Locations
|---ID---||---locationName---|
| 1 || Test1 |
| 2 || Test2 |
----------------------------
I've done some research, and I believe I need to modify JQuery to display an array of objects. I'm not too sure how to do this.
What would be the best way to have my auto complete list get the page ID from the SQL database and become clickable links?
You don't actually need for clickable links there. You can redirect the page within the autocomplete's select event , where you have access to the selected item object:
ui (Type: Object):
item (Type: Object):
An Object with label and value properties for the selected option.
ui.item.value will be the page ID generated with your PHP
$(".locationlist").autocomplete({
source : "search.php",
minLength: 1,
select : function(event, ui){
// You may need to change this part, as I don't know the exact values:
location.href = "http://your-site.com/" + ui.item.value;
}
});
As for your PHP, you can modify the output array like so:
while ($row = $stmt->fetch()) {
$return_arr[] = array(
'value' => $row['ID'],
'label' => $row['locationName']
);
}
I am trying to create a D3 line graph that will display a graph specific to the item that is selected in the drop-down menu. I have one script that queries my MySQL database and fills a drop-down menu with all of the correct options. From there, I want to click on an option and go to another page that creates a line graph based off of that selection. When I click on an option, I use json_encode to create a JSON object that should be compatible with D3.
I have another script that deals completely with drawing the graph and try to use d3.json to get the JSON object that is created when the specific selection is clicked. Whenever I try to load the graph page, it is completely blank. I am not sure if what I am trying to do is even possible. I have not tried including the drop-down in the same script as the one that creates the graph but do not think that I will be able to get the information from the database the same way.
Any guidance or suggestions would be greatly appreciated. I can post the code later if it is determined what I am trying to do is possible. Thanks!
EDIT:
This is the script that queries my database for the users that are put in the drop-down menu and then queries the database again for that selection's data. The drop-down menu has the desired result and the data is correctly echoed as well.
<?php
if (isset($_POST['name']))
{
$out = $_POST['name'];
$temp = explode(",", $out);
$populate_selection = "SELECT id, lastname, firstname FROM users WHERE id != '$temp[0]' ORDER BY lastname";
$out = $temp[1] . ', ' . $temp[2];
$student_hours = "SELECT ai_averages.user_id, ai_averages.title, ai_averages.hours FROM ai_averages INNER JOIN users ON ai_averages.user_id = users.id WHERE $temp[0] = ai_averages.user_id";
}
else
{
$temp[0] = " ";
$populate_selection = "SELECT id, lastname, firstname FROM users ORDER BY lastname";
$student_hours = "SELECT ai_averages.user_id, ai_averages.title, ai_averages.hours FROM ai_averages INNER JOIN users ON ai_averages.user_id = users.id WHERE $temp[0] = ai_averages.user_id";
$out = " ";
}
$result = $mysqli->query($populate_selection);
$option = "<option value= '{$temp[0]}'>$out</option>";
while($row = mysqli_fetch_assoc($result)) {
$option .= "<option value = '{$row['id']}, {$row['lastname']}, {$row['firstname']}'>{$row['lastname']}, {$row['firstname']} </option>";
}
if($student_results = $mysqli->query($student_hours))
{
$data = array();
for ($x = 0; $x < mysqli_num_rows($student_results); $x++)
{
//this array contains the data that I want in my graph
//the correct data is echoed every time that I click on the different choices
$data[] = mysqli_fetch_assoc($student_results);
}
echo json_encode($data, JSON_PRETTY_PRINT);
}
?>
<form id = "hello" method = "POST" >
<select name = "name" onchange = 'this.form.submit()'> <?php echo $option; ?> </select>
</form>
I then try and use d3.json("filename.php", etc) to get the information from the $data array but this has not worked.
I'm trying to create a nice and easy iterator and it worked at first, then I realized I'd need more information for the function so I tried to extend it and well it did not work.
Example Usage
$easyCMS->iterate($post,
echo $content[0];
echo $content[1];
);
Class Function
public function iterate($d,$fn){
$this->item = $d;
foreach($this->item as $post){
echo $fn;
}
}
Current Index.php Usage
$post = $easyCMS->my_query('SELECT * FROM `newsPost`');
//returns array
$easyCMS->iterate($post,
$content[0]."<br>",
$content[1]."<br>",
$content[2]."<br>",
$content[3]."<br>",
$content[4]."<br>",
);
//$post would be the first argument and after that would be what we want our function to do.
I get the error =>
Parse error: syntax error, unexpected ';' in .../index.php on line 23
Which I know that it's the constant $content[num] but I'd like to know how I'd do this for I know I could with JavaScript using the call method.
My database table looks something like
id: 1 == content: "Whats up" == ...etc
I want my code to iterate over these so then I can write like so
$easyCMS->iterate($post,
'<div class="hello">'.$content[0].'</div><div id="post_'.$content[1].'"><div class="content">'.$content[2].'</div>'
);
the error is caused by:
$easyCMS->iterate($post,
$content[0]."<br>";
$content[1]."<br>";
$content[2]."<br>";
$content[3]."<br>";
$content[4]."<br>";
);
which should be
$easyCMS->iterate($post,
$content[0]."<br>",
$content[1]."<br>",
$content[2]."<br>",
$content[3]."<br>",
$content[4]."<br>"
);
i don't think that this code solves your needs
Here is the best way for an easy iterator, took me some time but I finally solved it.
Class Function
public function iterate($d,$fn){
foreach($d as $item){
$txt = str_replace('{author}',$item["author"],$fn);
$txt = str_replace('{id}',$item["id"],$txt );
$txt = str_replace('{content}',$item["content"],$txt);
$txt = str_replace('{date}',$item["date"],$txt);
echo $txt;
}
}
PHP page IE index.php
$post = $easyCMS->my_query('SELECT * FROM `newsPost`');
$easyCMS->iterate($post,'<div class="hello">{author}</div><div id="post_{id}"><div class="content">{content}</div></div>');
$easyCMS->my_query is just a regular query which returns specific information
my_query
public function my_query($sql)
{
$array=array();//add an array
$query = mysqli_query($this->connect,$sql);
if($query > 0){
$c = mysqli_num_rows($query);//get how many rows there are
if($c > 1){//if greater than one push into the array
while($fetch = mysqli_fetch_array($query)){//while loop to push
array_push($array, $fetch);
}
return $array;
}else{
return mysqli_fetch_row($query);//rows is only one
}
}else{
return "No such query";//if the query does not exist!
}
}
Can't help but think you're over-complicating things here.
If you're using an array without an index key then it would be as simple as:
public function iterate($d,$fn){
foreach($d as $content){
echo $content;
}
}
Only if an index is key=>pair do you need to it like:
foreach ($d as $key=>$value) {
stuff//
}
$easyCMS->iterate($post,
'<div class="hello">'.$content[0].'</div>
<div id="post_'.$content[1].'"><div class="content">'.$content[2].'</div>'
);
Is wrong. When using " and ', you want to wrap ' inside of the ".
If, what you want is to irerate through a loop inside a loop, you'd want something like:
Foreach($post as $pos) {
$class->some_func($pos);
}
public function some_func ($post) {
/formatting.
echo $post;
/formatting.
}
The simplest I can come up with, based on your code currently is:
foreach($stuff_from_database_call as $content)
echo "formatting stuff". $content . "/close formatting";
Technically you could 1 line it, so long as dont mind using . to join strings :)
Note the lack of [0] [1] etc, which is un-needed, since you are iterating through the array. However, if it was a key=>pair you'd do it like this:
foreach($stuff_from_database_call as $key=>$content)
echo "formatting stuff". $key[$content] . "/close formatting";
Updated this after you wrote out and accepted your own answer. Instead of:
public function iterate($d,$fn){
foreach($d as $item){
$txt = str_replace('{author}',$item["author"],$fn);
$txt = str_replace('{id}',$item["id"],$txt );
$txt = str_replace('{content}',$item["content"],$txt);
$txt = str_replace('{date}',$item["date"],$txt);
echo $txt;
}
}
I'd suggest something more like:
public function iterate($d,$fn){
foreach($d as $item=>$value){
$txt = str_replace('{$value}',$item[$value],$fn);
echo $txt;
}
}
This will make it a LOT more flexible, as you can easily add fields, without having to touch the function itself. When coding, ALWAYS try and do so with as much forethought as you can, so you save yourself headaches down the road.
Either way, glad you got it sorted, and glad you came back to post your sollution.
1 last afterthought. Try naming your variables a little more reader friendly :) $d is nowhere near descriptive enough. Just another avoidable headache, for yourself and for anyone else having to look at your code :)