Dynamically change MYSQL query within a PHP file using jQuery .post? - php

Been trying this for quite a while now and I need help. Basically I have a PHP file that queries database and I want to change the query based on a logged in users name.
What happens on my site is that a user logs on with Twitter Oauth and I can display their details (twitter username etc.). I have a database which the user has added information to and I what I would like to happen is when the user logs in with Twitter Oauth, I could use jQuery to take the users username and update the mysql query to show only the results where the user_name = that particular users name.
At the moment the mysql query is:
"SELECT * FROM markers WHERE user_name = 'dave'"
I've tried something like:
"SELECT * FROM markers WHERE user_name = '$user_name'"
And elsewhere in the PHP file I have $user_name = $_POST['user_name'];. In a separate file (the one in which the user is redirected to after they log in through Twitter) I have some jQuery like this:
$(document).ready(function(){
$.post('phpsqlinfo_resultb.php',{user_name:"<?PHP echo $profile_name?>"})});
$profile_name has been defined earlier on that page.
I know i'm clearly doing something wrong, i'm still learning. Is there a way to achieve what I want using jQuery to post the users username to the PHP file to change the mysql query to display only the results related to the user that is logged in. I've included the PHP file with the query below:
<?php
// create a new XML document
//$doc = domxml_new_doc('1.0');
$doc = new DomDocument('1.0');
//$root = $doc->create_element('markers');
//$root = $doc->append_child($root);
$root = $doc->createElement('markers');
$root = $doc->appendChild($root);
$table_id = 'marker';
$user_name = $_POST['user_name'];
// Make a MySQL Connection
include("phpsqlinfo_addrow.php");
$result = mysql_query("SELECT * FROM markers WHERE user_name = '$user_name'")
or die(mysql_error());
// process one row at a time
//header("Content-type: text/xml");
header('Content-type: text/xml; charset=utf-8');
while($row = mysql_fetch_assoc($result)) {
// add node for each row
$occ = $doc->createElement($table_id);
$occ = $root->appendChild($occ);
$occ->setAttribute('lat', $row['lat']);
$occ->setAttribute('lng', $row['lng']);
$occ->setAttribute('type', $row['type']);
$occ->setAttribute('user_name', utf8_encode($row['user_name']));
$occ->setAttribute('name', utf8_encode($row['name']));
$occ->setAttribute('tweet', utf8_encode($row['tweet']));
$occ->setAttribute('image', utf8_encode($row['image']));
} // while
$xml_string = $doc->saveXML();
$user_name2->response;
echo $xml_string;
?>
This is for use with a google map mashup im trying to do. Many thanks if you can help me. If my question isn't clear enough, please say and i'll try to clarify for you. I'm sure this is a simple fix, i'm just relatively inexperienced to do it. Been at this for two days and i'm running out of time unfortunately.

At first, you should escape the $_POST you're inserting straight to the query:
'SELECT * FROM markers WHERE user_name = `' . mysql_real_escape_string($user_name) . '`';
As Erik suggests, don't throw out of the window the most useful warnings - most probably the answer will pop right ahead then.
But what I'm not quite sure about is the way your mashup works. It could get a lot easier if you just do all the stuff inside the php itself, omitting javascript at all. You might also want to check OAuth callbacks - should give you twitter id or user name.

There's nothing wrong with:
$result = mysql_query("SELECT * FROM markers WHERE user_name = '$user_name'");
Other then being ripe for SQL injection - it should work. You may want to try your query directly on the database and see if the results are what you expect.
I'd also recommend turning on error reporting during development. Add the following lines to the top of your document:
error_reporting(E_ALL);
ini_set("display_errors", 1);
and it will help you uncover many errors.

Related

automatically create new pages with php and mysqli

still getting my feet wet with php and mysqli, have so much to learn, but at this point this question is one of my most important priorities.
I did some research about this issue but am currently overwhelmed by pretty sophisticated stuff for my level, to be honest. I'd like to find the simplest most efficient way to "automatically" generate a great number of pages each with varying data in it.
the example of page 1's code below is extremely simplified, because the actual page actually has a lot more stuff, but the simplified example serves, I hope, to make my point.
<?php
$servername = "servername";
$username = "username";
$password = "password";
$db= "db";
$conn = mysqli_connect("servername","username","password","db");
$query = "SELECT word FROM demo WHERE group=1";
$result = $conn->query($query);
$row = mysqli_fetch_assoc($result);
$word = $row['word'];
echo $word;
?>
in my table I have / would have something like 500 entries (records?) in the 'group' column, numbered 1, 2, 3 etc all the way to 500.
for my specific purpose, I absolutely need to create as many online pages as there are groups -- in this example, 500 pages.
page 2's echo would have to refer to group 2, page 3's echo would have to refer to group 3, and so on.
obviously, there's a way to do this without copying and pasting the code 500 times and manually changing the group in each! haha. but what's the simplest way?
thank you in advance for any understanding and help, and either way, have an awesome day.
If I'm understanding you correctly, I believe you're waiting to create pages from the database Dynamically. You can use a get variable in the request http://yoursite.com/page.php?group=1.
Then in your code update your query to do:
$query = "SELECT word FROM demo WHERE group=".$_GET['group'];
That query is insecure, as any user could inject raw mysql into the $_GET['group'] variable.
$group = mysqli_real_escape_string($conn, $_GET['group']);
$query = "SELECT word FROM demo WHERE `group`='$group'";
This is much safer.
So PHP will look for a file called index.php by default in any directory that it accesses. You can place such a file in the root of public_html or www or where ever your site accesses. Now in this file you can do something like:
<?php
if($_GET['group']){ //Make sure you have the var
$query = "SELECT word FROM demo WHERE `group`=?"; //The query with param
if ($stmt = mysqli_prepare($conn, query){ // try it out
mysqli_stmt_bind_param($stmt, "i", $_GET['group']); // bind the data
$stmt->execute(); //run it
$result = $stmt->get_result(); // get results
//use result to echo and stuff
}
} else {
//Do something incase there is not a group specified.
echo "Nothing here";
}
?>
Now when you go to your site you will get something like 'localhost/index.php' and see Nothing here but if you type localhost/index.php?group='55' you will have access to the page 55 data in result.

PHP returning sql querystring, not an actual result?

got a slightly odd thing going on, not sure why. I have a PHP script which queries a MySQL DB for some user info.
Here is the offending code:
$activities = "SELECT sports FROM userActivityLocation WHERE user = '$userName'";
$result2 = mysql_query($activities);
$sports = mysql_result($result2,0);
When the POST goes through (http://www.websiteitshostedon.co.uk/API/getUserActivities.php?user=testtest123), the respons comes:
SELECT sports FROM userActivityLocation WHERE user = 'testtest123'Ultimate Volleyball
This is clearly not what I'm after, why is this happening?

Retrieve constantly from database

I am doing this animation tool where I fetch a value from my database and then a picture will animate to a certain position. My question is if it is possible to retrieve data constantly or like every 5 seconds?
Somehow like this:
while(autoretreive){
$data = mysql_query("select * from ......");
}
UPDATED from here
Thanks for your answers! Made it a little bit clearer what to do! Maybe I can explain better what I'm doing in my code.
I am doing this animation program as said, where balls with information is moving around to different locations. I have one value that will be updated frequently in the database, lets call it 'city'.
First at previous page I post the balls of information I want based on the 'city' and I do like this (simplified):
$pid = $_POST['id'];
$pcity[0] = $_POST['city'];
$pcity[1] = $_POST['city'];
$pcity[2] = $_POST['city'];
//...
$while(autoretrieve) { // HOW TO?
$data = mysql_query(select * from table where city == $pcity[0] OR $pcity == [1] //...);
while($rows = mysql_fetch_array($data)){
$city = $rows['city'];
$id = $rows['id'];
if($city == example1){
"animate to certain pos"; //attached to image
}
else if($city == example2){
"animate to certain pos"; //attached to image
}
}
}
So for every update in the database the image will animate to a new position. So a time interval of 5 seconds would be great. I'm not an expert in coding so sorry for deprecated code. Not so familiar with AJAX either so what is going to be imported to the code? It is also important that the page is not reloading. Just the fetch from database.
you can do it with ajax and javascript
make one javascript function which contains ajax code to retrive data from database
and at your page load using setTimeout call your ajax function at every 5 second
You can use sleep function to control how often you want to fetch data.
while(autoretreive){
$data = mysql_query("select * from ......");
//output your data here, check more in link about server sent events bellow
sleep(5);
}
Since you haven't specified how you plan to access data I'm writing this answer assuming Server-Sent Events as they are only ones that make sense according to your question.
Now all this was according to your question which wasn't very clear on how do you plan to use data. Again you'll most likely want to fetch data using ajax, but Server Sent Events can also be a good way you could achieve this.
And don't use mysql_* it's deprecated, switch to PDO or mysqli_*

PHP isnull First pass/Second pass flag

I have a PHP results page which starts off "first-pass" with ALL rows returned. It's a search listing of all pizza places in the county.
SELECT * from pizzeria;
Then the user can drill down into more detail... the page also has a CSS dropdown menu where the user can pick a specific neighborhood (which carries a URL):
href="samepage.php?neighborhood=HELLSKITCHEN"
which then changes the query after I pick up the $_GET[]
SELECT * from pizzaria WHERE nbh=(the $_GET[] variable sent in the URL);
but I'd like the page to call itself and I have header("Cache-Control:no-cache"); at the top.
I'm trying to create a first-pass or first visit flag variable with the isnull() function:
if (is_null($firstpass)) {
$query = SELECT all the records from the pizzaria table
} else {
$query = SELECT only the records WHERE I $_GET[] the value from the reloaded URL
}
It seems though that the $firstpass variable doesn't stick on reloads. Should I SESSION that variable? (though still have the problem of constantly resetting it)
Or maybe implement some other approach?
I know I can redirect to a separate second page and javascript back to this page to avoid "headers already sent", but I want to avoid the round-trip back to the client.
Is there a known best practice on reloads with new info? Kinda new to PHP here. thanks
Maybe I didn't understand well your problem but why wouldn't you do :
if (!isset($_GET['example'])) {
$query = 'SELECT * FROM pizzerias';
} else {
$query = 'SELECT * FROM pizzerias WHERE pizzeria = \'.mysql_real_escape_string($_GET['example']).\' LIMIT 1';
}
at the first pass because, it seem that the $_GET variable is set only when the user choose a pizzeria?
Here is a more targeted answer.
NOTICE: mysql_* functions are being depreciated, so use PDO instead. In my example I'm being semi-lazy and not using PDO.
//Connect to database and define table up here
...
if(!isset($_GET['neighborhood')){
$q = "SELECT * FROM pizzeria;";
}else{
$q = sprintf("SELECT * FROM pizzeria WHERE nbh=%s",mysql_real_escape_string($_GET['neighborhood']));
}
$query = mysql_query($q);
foreach($row = mysql_fetch_array($query,MYSQL_ASSOC){
//display the updated view of restaurants.
}
I would also suggest that you use jQuery for that Web 2.0 effect. It's really nice when you select from a drop-down menu and things magically move without a page reload.

Help in displaying data on user page. I think ive gone on a tangent here

I'm trying to display the data here in order of:
Author Name
Book Name
Url
NOTE: There are many results for each piece of data. Im not sure how they are stored in the array when they are fetched.
The database schema is relational as you will see and connects these bits of information from different areas of the database.
Im new to programming as you may have figured.
Im at a loss here.
Here is my code:
<?php
//Starting session
session_start();
//Includes mass includes containing all the files needed to execute the full script
//Also shows homepage elements without customs
include ('includes/mass.php');
//Set the session variable
$username = $_SESSION['username'];
//Check to see if logged in
if (isset($username))
{
//Check all databases assoc with the notes for username submissions
$sql_for_username_submission = "SELECT notes.authname, notes.bookname, notes.url, notes.note_id, notes.user, smallnotes.chapter_name FROM notes INNER JOIN small_notes ON notes.note_id = small_notes.notes_id AND notes.user = small_notes.user ORDER BY notes.note_id";
$get_data = mysql_query($sql_for_username_submission);
while ($data_row = mysql_fetch_assoc($get_data))
{
$authnames = $data_row['authname'];
Stopped here. not sure how to progress
}
}
?>
I would imagine you need some UI controls to which you would bind the data in data_row. In other words, you need to have some placeholders on the screen.
Best Regards
You are fetching my assosciative array so it does not matter. You can just reference the array item by key and use it whenever and where ever you want.
You do not have to worry about how the array is sorted.

Categories