I am trying to send two variables from an HTML page to a PHP script but the response keeps coming back as text/html. aka, the entire code in the PHP file is being returned to the console.
My jQuery code:
$.get( //call the server
"biography_query.php", //At this url
{
field: "value",
id: decodeURIComponent(id),
name: decodeURIComponent(name)
} //And send this data to it
).done( //And when it's done
function(data)
{
console.log(data);
},"jsonp"
);
PHP code:
header('Content-Type: application/json');
//start session on server to store the users information
session_start();
// establish connection to SQL database
$con = mysqli_connect("localhost","root","","capstone") or die("Error: " . mysqli_error($con));
$id = $_REQUEST['id'];
$name = $_REQUEST['name'];
// build statement to query database and return all characters
$SQL = "SELECT real_name, alternate_identities, aliases, nicknames, place_of_birth, first_appearance FROM `character` WHERE id='$id' AND superhero_name='$name'";
// execute the statement
$sqlReturn = mysqli_query($con, $SQL);
$row = array();
while($r = mysqli_fetch_assoc($sqlReturn)) {
$row['real_name'] = $r['real_name'];
$row['alternate_identities'] = $r['alternate_identities'];
$row['aliases'] = $r['aliases'];
$row['nicknames'] = $r['nicknames'];
$row['place_of_birth'] = $r['place_of_birth'];
$row['first_appearance'] = $r['first_appearance'];
}
echo json_encode($row);
"I am using <? tags"
As per OP's wishes: (to close the question, and for future readers)
If short open tags are not enabled, you will need to either enable them, or change <? to <?php.
Here are a few articles on the subject, on Stack:
How to enable PHP short tags?
Enable PHP short open tags via .htaccess
On PHP.net:
http://php.net/manual/en/ini.core.php
Related
I will use data form my database to use it later in a JS function. To get the data form the database I use sql request in php, then copy it in json but I dont get the value of my request.
I'm opening my database With following code:
<?php
$db = new PDO("sqlite:Playerbase.db");
$info = $db ->query("SELECT Gamertag FROM player WHERE Highscore = 999");
$info_json = json_encode($info);
file_put_contents("Highscoreliste.json", $info_json);
echo '<script type="text/javascript">Highscoreliste();</script>';
//I want to open the .json in this js funktion and use the informaton from the request.
header("Location: index.html");
?>
But I dont get the real data in my .json, the value of the .json is:
{"queryString":"SELECT Gamertag FROM player WHERE Highscore = 999"}
Why am I just getting the Request copied in my .json and not the value of the request ? and how can I fix it ?
Here you can find more infos, how to use PDO : https://www.php.net/manual/en/pdo.query.php
Then here, there is a example how you can add JSON data into HTML, from Php :
<?php
$pdo = new PDO("sqlite:Playerbase.db");
$stmt = $pdo->query("SELECT Gamertag FROM player WHERE Highscore = 999");
$data = $stmt->fetchAll();
header("Location: index.html");
echo '<script type="text/javascript">const JSONDATA = ' . json_encode($data) . ';';
echo 'Highscoreliste(JSONData);</script>';
?>
But a better ways is to make an Ajax request to fetch your data from your Backend.
I want to update database with flash (text input)
Here is my php code
<?php
mysql_pconnect ("localhost", "root", "");
mysql_select_db ("adaptasi");
$isi = isset($_POST['OutData']);
$query2 = "UPDATE materi SET isi='$isi' WHERE id = 1";
$result2=mysql_query($query2) or die("Query Failed : ".mysql_error());
?>
Here is my Actionscript 2
function SubmitData()
{
trace("Sending");
var OutData = new LoadVars();
text_morfologi.text = OutData.OutData;
filepath = "http://localhost/adaptasi/";
OutData.sendAndLoad(filepath + "editmorfologi.php", OutData, "POST");
}
btnsave.onRelease = function()
{
SubmitData();
btnedit.visible = true;
btnsave.visible = false;
};
But the result isi in database is '1' not the text that I input in the text field.
Thanks
You have some problems in your code :
ActionScript 2 :
To send data using a LoadVars object you have to attache it to that object as its properties, and if you want to receive a response from your server side script, you can use LoadVars.sendAndLoad() but if you want just to send that data without waiting for any response, you can use LoadVars.send().
Supposed that you will use sendAndLoad() function, so you code can be like this :
var url:String = 'http://www.example.com/update.php';
// the LoadVars object that will receive (load) a response from the server
var receiver:LoadVars = new LoadVars();
receiver.onLoad = function(success:Boolean)
{
if (success) {
trace(receiver.response); // gives for example : update successful
} else {
trace('error');
}
}
// the LoadVars object which will send (post) some data to the server
var sender:LoadVars = new LoadVars();
sender.id = txt_id.text;
sender.name = txt_name.text;
sender.sendAndLoad(url, receiver); // we don't set the method to POST because that's its default value
PHP :
As mentioned in many comments, the PHP's isset() function is used to verify if a variable is set and is not NULL and it returns a boolean value ( TRUE of FALSE ) which is when it's casting (converting) to a string will give you 1 for TRUE and `` (empty string) for FALSE.
In your case, and according to you, I think that as the the variable $_POST['OutData'] is apparently set, isset($_POST['OutData']) is true which will set the value of $isi to 1, so you will get :
$query2 = "UPDATE materi SET isi='1' WHERE id = 1";
but according to your posted code, I think that you should get :
$query2 = "UPDATE materi SET isi='' WHERE id = 1";
Returning now to our current example, we will get our two POST variables (id, and name) sent by the AS2 script to update the DB and then return a response if the data has been successfully updated or not :
<?php
if(isset($_POST['id'] && isset($_POST['name']))
{
$id = $_POST['id'];
$name = $_POST['name'];
mysql_pconnect('localhost', 'root', '');
mysql_select_db('my_db');
$query = "UPDATE users SET name = '$name' WHERE id = $id";
$result = mysql_query($query);
if($result){
echo 'response=update successful';
} else {
echo 'response=update failed';
}
}
?>
Of course here I tried just to give you a very simple example of a working code according to your current one. You should know that for your PHP side that the "mysql" extension was deprecated in PHP 5.5.0 and was removed in PHP 7, so you should think to use "mysqli" or "PDO" extensions, for more about that, take a look here, also don't forget to sanitize, validate and escape any user's data, ... and for the ActionScript side, maybe it's the time to start learning ActionScript 3 ...
Hope that can help.
if(isset($_SESSION['admin'])) {
echo "<li><b>Admin</b></li>";
}
<?php
session_name('MYSESSION');
session_set_cookie_params(0, '/~cgreenheld/');
session_start();
$conn = blah blah
$query2 = 'Select Type from User WHERE Username = "'.$_SESSION['user'].'" AND Type =\'Admin\'';
$result2 = $conn->query($query2);
if($result2->num_rows==1) {
$_SESSION['admin'] = $result2;
}
?>
Hi, I'm trying to set this session variable but it doesn't seem to be setting, and i'm wondering if anyone can help. If session['admin'] isset it should echo the admin button.
But i'm not quite sure why? (I do have session start and everything on everypage, it's not a problem with that or any of the "You don't have php tags" I have checked the mysql query, and it does return something from my table. Any ideas please?
Your session_start(); should be at the top of the page before anything to do with the session variables.
From the docs:
When session_start() is called or when a session auto starts, PHP will call the open and read session save handlers.
Edit from comments:
<?php
session_name('MYSESSION');
session_set_cookie_params(0, '/~cgreenheld/');
session_start();
// Moved to start after answer was accepted for better readability
// You had the <?php after this if statement? Was that by mistake?
if(isset($_SESSION['admin']))
{
echo "<li><b>Admin</b></li>";
}
// If you have already started the session in a file above, why do it again here?
$conn = blah blah;
$query2 = 'Select Type from User WHERE Username = "'.$_SESSION['user'].'" AND Type =\'Admin\'';
// Could you echo out the above statement for me, just to
// make sure there aren't any problems with your sessions at this point?
$result2 = $conn->query($query2);
if($result2->num_rows==1)
{
$_SESSION['admin'] = $result2;
// It seems you are trying to assign the database connection object to it here.
// perhaps try simply doing this:
$_SESSION['admin'] = true;
}
?>
Edit 2 from further comments:
You have to actually fetch the fetch the data like this - snipped from this tutorial which might help you out some more:
$query = "SELECT name, subject, message FROM contact";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo "Name :{$row['name']} <br>" .
"Subject : {$row['subject']} <br>" .
"Message : {$row['message']} <br><br>";
}
But having said that, while we are talking about it, you would be better off moving away from the old mysql_* functions and move to PDO which is much better.
Move session_start(); to the top of the page. You are trying to retrieve sessions, where it's not loaded.
EDIT: Try echoing $_SESSION['admin'], if it even contains something. Also try debugging your if($result2->num_rows==1) code by adding echo('its working'); or die('its working'); inside it, to check if $result2 contains exactly 1 row, since currently it seems $result2 contains either more than 1 row or no rows at all.
I have this php code :
$kid = $_GET['document'];
$url = $_GET["url"];
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("repository", $con);
$url = mysql_real_escape_string($url);
$url = htmlspecialchars($url);
$exists = mysql_query("SELECT url FROM url WHERE url = '$url' LIMIT 1");
if (mysql_num_rows($exists) == 1) {
mysql_query("DELETE FROM url WHERE url = '$url'" );
mysql_query("DELETE FROM paragraphs WHERE url = '$url'" );
}
require("/htmlpurifier-4.3.0-standalone/HTMLPurifier.standalone.php");
require("/htmlpurifier-4.3.0-standalone/HTMLPurifier.autoload.php");
include("simple_html_dom.php");
$html = file_get_html($url);
$purifier = new HTMLPurifier();
$body = $html->find('body', 0);
echo $html->find('title', 0);
$cleanbody= $purifier->purify($body);
echo $cleanbody;
echo '<script src="jquery.js" type="text/javascript"></script>';
echo '<script src="extract.js" type="text/javascript"></script>';
$html->clear();
unset($html);
What happens here is that an html file is loaded, the body is found, purified, and is extracted by "extract.js" (which calls another php script to load it into a database). What I want to happen now is get the url_id (auto incrementing field) of the inserted url and then do a redirect after ALL of this is complete (executing a mysql_query and then a header location redirect, seems to be doing this before anything is loaded into the database). Perhaps running a mysql_query for the url_id where it matches the given url, after some condition satisfies the data has finished loading?
You don't seem to understand the server/client principle. You need to remember that the PHP just generates some HTML and sends it to the client. You can't know when the client will request the execution of the other PHP script.
Furthermore, you need to learn more SQL. It doesn't make sense to use a SELECT just to detect if a row exists, and then DELETE it if it does, not using the result at all. You might as well just run the DELETE statement no matter what. If you want to know whether it DELETE'ed anything, use mysql_affected_rows(). Also, consider using prepared statements, as it make it easier to protect against SQL injection.
If the extract.js is just extracting some tag from the HTML (without user input), you could do that on the server-side, and you wouldn't have to send it to the client at all.
This is probably easy for you guys, but I can't understand it.
I want to save the filename of an image to it's own row in the SQL base.
Basically, I log on to the site where I have my own userID.
And each user has its own column for background images. And the user can choose his own image if he wants to. So basically, when the user clicks on the image he wants, a jquery click event occurs and an ajax call is made to a php file which is supposed to take care of the actual update. The row for each user always exist so there's only an update of the data that's necessary.
First, I collect the filename of the css property 'background-image' and split it so I get only the filename. I then store that filename in a variable I call 'filename' which is then passed on to this jQuery snippet:
$.ajax({
url: 'save_to_db.php',
data: filename,
dataType:'Text',
type: 'POST',
success: function(data) {
// Just for testing purposes.
alert('Background changed to: ' + data);
}
});
And this is the php that saves the data:
<?php
require("dbconnect.php");
$uploadstring = $_POST['filename'];
mysql_query("UPDATE brukere SET brukerBakgrunn = '$uploadstring' WHERE brukerID=" .$_SESSION['id']);
mysql_close();
?>
Basically, each user has their own ID and this is called 'brukerID'
The table everything is in is called 'brukere' and the column I'm supposed to update is the one called 'brukerBakgrunn'
When I just run the javascript snippet, I get this message box in return where it says:
Background changed to:
Warning: session_start() [function.session-start]:
Cannot send session cache limiter -
headers already sent (output started
at
/var/www/clients/client2/web8/web/save_to_db.php:1)
in
/var/www/clients/client2/web8/web/access.php
on line 3
This is dbconnect.php
<?php
$con = mysql_connect("*****","******","******");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("****", $con);
require("access.php");
?>
And this is access.php:
<?php
// Don't mess with ;)
session_start();
if($_REQUEST['inside']) session_destroy();
session_register("inside");
session_register("navn");
if($_SESSION['inside'] == ""){
if($_POST['brukernavn'] and $_POST['passord']){
$query = "select * from brukere where brukerNavn='" . $_POST['brukernavn'] . "' and brukerPassord = md5('" . $_POST['passord'] ."')";
$result = mysql_query($query);
if(!$result) mysql_error();
$rows = #mysql_num_rows($result);
if($rows > 0){
$_SESSION['inside'] = 1;
$_SESSION['navn'] = mysql_result($result,"navn");
$_SESSION['id'] = mysql_result($result,"id");
Header("Location: /");
} else {
$_SESSION['inside'] = 0;
$denycontent = 1;
}
} else {
$denycontent = 1;
}
}
if($denycontent == 1){
include ("head.php");
print('
<body class="bodylogin">
content content content
</body>
');
include ("foot.php");
exit;
}
?>
Big security issue!
You didn't quote and escape the input to the MySQL query. I could easily hack the end, stack another query, and delete your entire database!
Also, you're missing the ending parenthesis at the end of mysql_query().
mysql_query("UPDATE brukere SET brukerBakgrunn = $uploadstring WHERE brukerID=" .$_SESSION['id'] ."";
should be
mysql_query("UPDATE brukere SET brukerBakgrunn = $uploadstring WHERE brukerID=" .$_SESSION['id']);
closing parenthesis is missing and the quotes ("") are useless.
Read about SQL injection in order to make your application safe.
EDIT:
<?php
require("dbconnect.php")
?>
<?php
This code sends (the part between ?> and <?php) a newline to the output (it's the same as echo "\n") which is not allowed if you want to write to a session variable consequently.
Remove the empty line before session_start():
?>
<?php
The original error is due to a missing semicolon on the require line.
As others have said, you need to learn about sql injection and using placeholders. Get out of the habit of using submitted data without using placeholders or escaping first.
<?php
//require_once("dbconnect.php");
$uploadstring = $_REQUEST['filename'];
$db_pswd = 'xxx-xxx-xxx';
$db_user = 'john_doe';
$db_table = 'my_table';
$con = mysql_connect( 'localhost' , $user , $pswd );
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db( $db_table , $con );
mysql_query(" UPDATE brukere SET brukerBakgrunn = '".$uploadstring."'
WHERE brukerID = '".$_SESSION['id']."' ");
mysql_close($con);
?>
I think you need to use a fresh code! yours is compromised! ;-))
you forgot the closing ')' in your mysql_query line !
mysql_query("UPDATE brukere SET brukerBakgrunn = $uploadstring WHERE brukerID=" .$_SESSION['id'] );
You don't need the ."" at the end of your query too.
require("dbconnect.php")
should be
require("dbconnect.php");