I'm trying to get PHP code like this to work:
<?php
$hostname = '******';
$database = 'firstdb';
$username = '*****';
$password = '*****';
$dbh = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
$sortvalue = "datbase_percent";
$sortorder = "ASC";
$sql = "select * from advanced_data where category like age_group order by {$sortvalue} {$sortorder};";
$result = $dbh->query($sql)->fetchAll(PDO::FETCH_ASSOC);
header('Content-type: application/json');
echo json_encode($result);
?>
What I want to be able to do is define the $sortvalue and $sortorder via an AJAX call. I'm getting it now like this:
$.getJSON('all_get_2.php', function(data) {
Two questions...my PHP code doesn't work because I can't figure out the proper syntax for building the $sql variable the makes up the mySQL query. I've tried a bunch of things, but keep getting 500 errors. If I just type in the values, then the code works, so I know it's just a problem with my syntax.
Second question...what's the best way to pass a variable into $sortvalue and $sortorder from my front end? I know it's something using $.ajax, but not sure of the best way to do it. The idea is that the user would click a button, which corresponds with sorting a chart ascending or descending and reloads the chart without reloading the page. Any direction here would be appreciated.
Related
I built a simple chat app earlier with PHP and JavaScript (using setTimeout with AJAX requests) and now I am looking to moving into PHP websocket. I have headed and I am looking through libraries such as Ratchet and socket.io. But I want to know if a simple PHP query such as INSERT or SELECT can be executed easily with websocket. Say I have a simple
send.php
session_start();
require_once ("db.php");
$db = new MyDB();
$user = $_SESSION['logged_in_user'];
$message = $_POST['user_message'];
$stmt = $db->exec("INSERT INTO table (message) VALUE($message)");
get.php
session_start();
require_once ("db.php");
$db = new MyDB();
$user = $_SESSION['logged_in_user'];
$stmt = $db->query("SELECT message FROM table WHERE user = '$user'");
while ($row = $stmt->fetchArray(SQLITE3_ASSOC)
{
$usermessage = $row['message'];
echo $usermessage;
}
Is there a simple way of using websocket to execute this or do I still have to use a PHP websocket library for this?
I know about prepared statements.
This is page of wordpress I am adding core php code for displaying data into table as per select input for that I am using javascript for gettin input and pass to the page page.And that page getting value as per value fir a mysql query.But my core php code dispaly as it is on screen. I am not able to understand how to do this. Beacuse I am new in wordpress Today is my first day in wordpress. Please help me ..Thanks in advance
<?php
$var=$_COOKIE['v'];
$id = explode(",", $var);
echo 'hawno:'.$id[1];
$conn = mysql_connect("localhost", "root", "");
$db = mysql_select_db("shepherddb");
$err = error_reporting(E_ALL && ~E_NOTICE);
$result=mysql_query("select ship_id,track_id,track_ship_id,track_mod_of_transport,track_location,track_status from
tracking,shipment");
while($data = mysql_fetch_array($result)) {
print_r($data);
}
?>
You need to use $wpdb global object provided by wordpress.
For example ,
global $wpdb;
$results = $wpdb->get_results( 'SELECT * FROM wp_options WHERE option_id = 1', OBJECT );
You can also use pre_get_posts action to modify the POSTS Query.
add_action( 'pre_get_posts', 'your_theme_function' );
Let me know if you need more information on the same.
I'm trying to create a session variable joomla style with ajax when checkboxes are selected. Here is my code in the select_thumb.ajax.php file:
$_SESSION['ss'] = $value;
$response = $_SESSION['ss'];
echo $response;
}
exit;
// Get db connection
$db = JFactory::getDbo();
//create new query object
$query = $db->getQuery(true);
//Prepare insert query
$query
->insert($db->valueChbx('download_variable'))
// Set the query using populated query object and execute it.
$db->setQuery($query);
$db->execute();
?>
Here is my HTML for the checkboxes:
<input type="checkbox" id="thumbselect" name="valueChbx" class="checkbox" value="/import/images/'+data[i]['filename']+'">';
I haven't coded the ajax through javascript yet because I'm wondering if i should use onFocus? There could be multiple checkboxes selected. Thanks for any help in advance.
Do not use PHP's default session variable in Joomla application use its native factory for that.
Set a session variable
$session = JFactory::getSession();
$session->set('name', "value");
Get a session variable
$session = JFactory::getSession();
echo $session->get('name');
more .
hope it helps..
Hello I am trying to output my mysqli database to a js file after encoding it, I have no trouble encoding it with json_encode but how can I get it into a js file (updating every time the mysqli data is updated)
$mysqli = new mysqli('localhost','user','password','myDatabaseName');
$myArray = array();
if ($result = $mysqli->query("SELECT * FROM tablename")) {
$tempArray = array();
while($row = $result->fetch_object()) {
$tempArray = $row;
array_push($myArray, $tempArray);
}
echo json_encode($myArray);
}
$result->close();
$mysqli->close();
Any help or insight would be great! thanks
To return a json file you will have to set json headers at the top of your PHP code:
header('Content-Type: application/json');
If you just want to write the json code into an external file you would have to use PHPs fwrite().
However you can't automatically update the file, when the database is updated. You need to call your PHP file in order to update the json file.
Maybe you can solve this by using a MySQL trigger in your database, more information here.
It appears that json_encode is being VERY picky about what other stuff can be inside my PHP file. Which is fine, because I just do what I normally would do in file A (with json_encode) in it's own file.
I just thought I would ask because I am storing a variable in the $_SESSION instead of updating my database with the variable because json_encode doesn't seem to want to work when I have all of the code in its file.
For instance, this code doesn't work:
<?php
session_start();
include 'dbcon.php';
$sessionID = uniqid();
echo json_encode($sessionID);
if(isSet($_POST['clearSession']) == '1')
{
$query = "UPDATE currentID SET id=('0')";
$execute = $mysqli->query($query) or die($mysqli->error.__LINE__);
} else {
$query = "UPDATE currentID SET id=('$sessionID')";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
}
?>
When going to the file in my browser, I do in fact get the json_encode results, however when my Javascript calls it it doesn't seem to correctly import it.
So, for now I simply have two PHP files:
<?php
session_start();
$sessionID = uniqid();
$_SESSION["sessionID"] = $sessionID;
echo json_encode($sessionID);
?>
Which echo's the same thing as in the first file, but this time my JavaScript correctly imports it.
and
<?php
session_start();
include 'dbcon.php';
if(isSet($_POST['clearSession']) == '1')
{
$query = "UPDATE currentID SET id=('0')";
$execute = $mysqli->query($query) or die($mysqli->error.__LINE__);
} else {
$sessionID = $_SESSION["sessionID"];
$query = "UPDATE currentID SET id=('$sessionID')";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
}
?>
I guess my question is, why does this happen? It seems kind of silly that I have to store the uniqid in a SESSION so that my other PHP file can add it to the database. Whereas if I simply had it in one file, then I could just update the database when I generate a new uniqid and avoid having to use $_SESSION in the first place.
You have this:
$sessionID = uniqid();
echo json_encode($sessionID); // "53d4c17abfe87"
Since uniqid() produces a plain string, your output is not valid JSON as per the format specification. You'll need something like this instead:
$sessionID = uniqid();
echo json_encode(array($sessionID)); // ["53d4c17abfe87"]
Why does json_encode() generate invalid JSON in the first place? Because some times it's useful to generate partial JSON. For instance, it's a handy trick to inject values into generated JavaScript code:
var foo = <?=json_encode($sessionID)?>;
It's also documented:
PHP implements a superset of JSON - it will also encode and decode
scalar types and NULL. The JSON standard only supports these values
when they are nested inside an array or an object.
So to answer the question title:
Is json_encode extremely picky?
On the contrary, it's fairly relaxed!
You don't need to store it in a session necessarily, it's the fact that $_SESSION is an array.
So, what you would want would be something like this:
echo json_encode(array('sessionID' => $sessionID));
And then when you parse the JSON with JavaScript you can access it like this:
obj = JSON.parse(jsonObj);
alert(obj.sessionID);
Obviously, jsonObj is the JSON passed from the server.
Hope this helps!