So today I have another small little issue with my PHP, that is causing me to get a server error. You see, I have this javascript function:
$.post('script.php', { limit: str }, function(result) {
console.log(result);
});
which of course makes a call to my php file:
require_once("../data/db-settings.php");
require_once("../data/file.php");
global $pdo;
$list = array();
$limit = $_POST["limit"];
chop($limit, ";");
$stmt = $pdo->prepare("SELECT cust_id, cust_addr FROM project WHERE " . $limit . " = cust_id");
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$list[] = $row;
}
echo $list;
The point of the php is to grab some information from a database that a user can dynamically change and use. The issue, I'm assuming, is with how I'm using PDO, because the code I'm using is in working order in another section. I also know that my function call is sending data and working properly, because when I check for just what I send, it sends properly.
Thanks for any help guys.
Check your query FROMproject can not be together.
Your query should look like this:
$pdo->prepare("SELECT cust_id, cust_addr FROM project WHERE " . $limit . " = cust_id");
It is an unobvious error!
So you step by step following the : http://pcsupport.about.com/od/findbyerrormessage/a/500servererror.htm
PDO doesn't throw Internal server error. Must be require_once.
checkout db-settings.php and file.php files. Require_once throws 500 error if it can't find files.
If the paths are correct, then check out included files.
proper way: check your log files.
Related
I am setting up a login page to take a users username and password then check that against a local database, however nothing is echoing form the database connection and there is no redirecting to the next page 'welcome.php' happening.
I have already tried many different ways of connecting to the local database and redirecting to different pages with different methods, none of which gave any error message or worked. using XAMPP Apache and mySQL modules to provide the local server.
<?php
if (isset($_POST['Login']))
{
$link = mysql_connect('localhost','root','password','budget');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
session_start();
$username= $_POST['username'];
$password= sha1($_POST['password']);
$_SESSION['login_user']=$username;
$query = mysql_query("SELECT accounts.username, passwords.password_hash
FROM accounts
INNER JOIN passwords ON accounts.account_id = passwords.account_id
WHERE accounts.username = '$username' AND password_hash = '$password';");
if (mysql_num_rows($query) != 0){
?>
<script type="text/javascript">window.location.replace(welcome.php);
</script>;
<?php
mysql_close($link);
}
}
?>
I expect it to redirect to 'welcome.php' but instead it just refreshes the same page and nothing is echoed or given as an error
What isn't working?
Your JavaScript location.replace method needs a string as an input, you're not giving it that (as the input value is not quoted). It would be window.location.replace('welcome.php'); instead.
How to solve it?
The better solution is to redirect in PHP instead of in JavaScript, using header().
Additional remarks
I took the liberty of converting your code to use mysqli_ instead of the old, outdated and deprecated mysqli_ library. With this, you can use a prepared statement, as I have shown below. Use this approach for all your queries, bind the parameters through placeholders.
session_start();
if (isset($_POST['Login'])) {
$link = mysqli_connect('localhost','root','password','budget');
if ($link->connection_errno) {
die('Could not connect: ' . $con->error);
}
$username = $_POST['username'];
$password = sha1($_POST['password']);
$stmt = $link->prepare("SELECT a.username, p.password_hash
FROM accounts a
INNER JOIN passwords p
ON a.account_id = a.account_id
WHERE a.username = ?
AND p.password_hash = ?");
$stmt->bind_param("ss", $username, $password);
$stmt->bind_result($resultUsername, $resultPassword);
$stmt->execute();
if ($stmt->num_rows) {
$_SESSION['login_user'] = $username;
header("Location: welcome.php");
}
$stmt->close();
}
What's next?
Fix your passwords. Using sha1() is highly insecure for passwords, look into using passwords_hash()/password_verify() instead.
You need to add single quote around welcome.php
As welcome.php is neither a JavaScript keyword like this nor a number, single quote is mandatory also it is not a variable/object.
JS considers welcome as object and php as its method in welcome.php
Without it, a JavaScript error will be displayed:
ReferenceError: welcome is not defined
<script type="text/javascript">window.location.replace(welcome.php);
</script>
Also, there is no need of semi-colon ;.
JavaScript redirect without any condition.
I've got a piece of javascript as follows:
$.ajax({
type:"get",
url:"http://www.orc23.com/get.php",
data: { solution: src },
datatype: "json",
success: function(returndata){
alert(returndata);
}
});
And this is the corresponding php file that interacts with mysql:
<?php
$con = mysqli_connect("orc23com.fwdsfawmsdfaysql.com","ssft","dsfss123","cookies");
if (!$con)
{
die('Could not connect: ' . mysqli_connect_error());
}
mysqli_select_db($con, "cookies");
$sql="SELECT SOLUTION FROM requests WHERE theurl = '$_GET[solution]')";
$result=mysqli_query($con,$sql);
$num_rows=mysqli_num_rows($result);
$row = mysqli_fetch_array($result);
$returndata=json_encode($row);
echo $returndata;
mysqli_close($con)
?>
The variable "src" I am passing in is a URL (string) , so I believe I should be treating it in a different way b/c of the nature of an URL with all its' special characters ,,,, I am running my code and it errors out as a "null" , but when I run the appropriate sql statement query in mysql DB then the DB returns what I am expecting ..... please advise what I may be doing wrong please ?
the sql I am running is this:
SELECT solution
FROM requests
WHERE theurl = 'https://www.google.com/fskdfalkadsl?=sksdkalsk&soccer=uwiw'
;
I know it will return back to me single row with just one column , and know what to expect as the value , but I can't seem to get the "get.php" page to return anything but "null" it seems ....
You get NULL because PHP does not automatically populate the $_GET when it receives JSON formatted data, so there is nothing in $_GET['solution']. You need to capture and decode the input yourself.
Instead of:
$solution = $_GET['solution'];
You need
$data = json_decode(file_get_contents('php://input'), true);
$solution = $data['solution'];
Or something close to it.
Sorry if this is still another thread on the subject but I am struggling since hours but could not find the solution.
I am trying to get data from a Mysql database, create a JSON with php, then parse this JSON in javascript.
Here is my json.php
<?php
$link = mysql_pconnect("localhost", "root", "") or die("Could not connect". mysql_error());
mysql_select_db("people") or die("Could not select database");
$arr = array();
$rs = mysql_query("SELECT * FROM nom");
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
echo '{"users":',json_encode($arr),'}';
/*
//The json object is :
{"users":[{"id":"1","prenom":"Alain","age":"23"},{"id":"2","prenom":"Bruno","age":"24"}]}
*/
?>
Then I try to parse it into java
<div id="placeholder6"></div>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
$.getJSON('http://localhost/json.php', function(data) {
var output="<ul>";
for (var i in data.users) {
output+="<li>" + data.users[i].id + " " + data.users[i].prenom + "--" + data.users[i].age+"</li>";
}
output+="</ul>";
document.getElementById("placeholder6").innerHTML=output;
});
</script>
when I replace localhost/json.php by the result in a file data.json, it works, when I open localhost/json.php with firefox, I can see the JSON table...so I do not know why it does not work with localhost/json.php.
Is my php code or javascript code wrong ?
Thanks in advance for your help !
Try this method
var users= data.users;
$.each(users,function(index,users){
console.log(users.prenom); /// and users.id etc
})
Try This in php
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
$return = new stdClass();
$return ->users = $arr;
echo json_encode($return);
I think your web application server (like Apache or nginx) sends Content-Type: text/html by default or something of that sort for your json.php file. On the other hand, it looks like $.getJSON method requires a application/json content type field.
Try adding:
header("Content-Type: application/json");
to the top of the json.php file.
Edit - additional info:
I couldn't find in the original documentation of the $.getJSON method whether it, in fact, requires the specific Content-Type so I looked into the source code:
https://github.com/jquery/jquery/blob/1.7.1/src/ajax.js#L294
Here is the line of source code for jQuery 1.7.1 (which is the version you said that you use, I hope) for getJSON and as you can see, it calls jQuery.get with the last argument set to "json".
In turn, the jQuery.get documentation reveals that this argument means:
The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html).
from: http://api.jquery.com/jQuery.get/
Thus, when you call $.getJSON("/url/to/file", ...) that first argument is expected to be a JSON. If you add the PHP code from the top of my answer, your web application server will mask the output of the php file as a JSON.
I am trying to retrieve a single row from a MySQL table using a mysqli statement. I've tried several different iterations of code, subtly changing the structure based on various previous questions from this forum, and others, but can't seem to get any result other than 'null'.
This is part of a larger script which is called via an Ajax request with jQuery. I've included both the PHP and the Javascript below, though I'm fairly confident in the JS being OK (preparing to be told otherwise now...).
Any suggestions as to where I'm going wrong would be very much appreciated as I can't see the wood from the trees anymore, and am just going around in circles.
PHP:
//initiate new mysqli object
$retrieve_link = new AuctionMySQLi($db_host, $db_user, $db_password, $db_name); //custom subclass, this definitely works as is used in other scripts on the server
//prepares DB query. Query has been tested on phpmyadmin and returns the expected data set
$stmt = $retrieve_link->prepare("SELECT `item_number`,`item_name`,`item_category`,`end_date`,`auction_type`,`high_bid_number` FROM `item` WHERE `item_number`=2");
$stmt->execute(); //no params to bind, so execute straight away
$stmt->bind_result($item);
$stmt->fetch();
$dataset = $item->fetch_row();
$response[0] = $dataset; //returned data forms part of larger dataset
echo json_encode($response); //return the entire dataset to a jquery Ajax request
die;
JS:
//this definitely works as objects have been returned via the 'success' function as the code was being developed
$.ajax({
url : "items/populate-home-page-script.php",
type : "GET",
data : {data:toSend},
dataType : "json",
success : function(data){
alert(data[0]);
},
error : function(jqXHR, textStatus, errorThrown){
alert(textStatus+','+errorThrown);
}
});
return false;
I have also tried using fetch_assoc() and fetch_row() as part of the PHP query, taking direction from the PHP reference material here and here. I have also read through these questions from Stackoverflow this, this, and this, but I still seem to get a return of null for every different code combination I try.
As I've said in a code comment, I know that the link to the DB works as I've used it in other scripts, and in other areas in this script - so there's no reason why this object wouldn't work either. I also know that the query returns the expected data when inputted to phpmyadmin.
The returned data is just a number of strings, any all I would like to do is store around 16 returned datasets to an array, as part of a loop, and then return this array to the Ajax request.
You are using "AuctionMySQLi" which appears to extend the regular Mysqli driver. I'll assume it does this correctly.
You're using prepared statements which is probably an overkill in this case. You could accomplish the same thing with something like this (php 5.3, mysqli + mysqlnd):
$retrieve_link = new AuctionMySQLi($db_host, $db_user, $db_password, $db_name);
$result = $retrieve_link->query("SELECT `item_number`,`item_name`,`item_category`,`end_date`,`auction_type`,`high_bid_number` FROM `item` WHERE `item_number`=2");
if($result !== false) {
echo json_encode($result->fetch_all());
} else {
echo json_encode(array());
}
$retrieve_link->close();
If you're using an older php version, or mysqlnd is not available, you can also do
$retrieve_link = new AuctionMySQLi($db_host, $db_user, $db_password, $db_name);
$result = $retrieve_link->query("SELECT `item_number`,`item_name`,`item_category`,`end_date`,`auction_type`,`high_bid_number` FROM `item` WHERE `item_number`=2");
if($result !== false) {
$output = array();
while($row = $result->fetch_assoc()) {
$output[] = $row;
}
echo json_encode($output);
} else {
echo json_encode(array());
}
$retrieve_link->close();
I also understand that you want to limit the number of results. In both cases, a good way of getting it done is to use a LIMIT statement in SQL. This is lower the overhead overall at source. Otherwise you can array_slice to slice the output of result->fetch_all() in solution 1, or $output in solution 2.
Finally, if you insist in using prepared statement read the note at
http://ca2.php.net/manual/en/mysqli-stmt.bind-result.php
and analyze provided example:
$retrieve_link = new AuctionMySQLi($db_host, $db_user, $db_password, $db_name);
$stmt = $retrieve_link->prepare("SELECT `item_number`,`item_name`,`item_category`,`end_date`,`auction_type`,`high_bid_number` FROM `item` WHERE `item_number`=2");
$stmt->execute();
$stmt->bind_result($itemName, $itemCat, $endDate, $auctionType, $highBidder);
$output = array();
while($stmt->fetch()) {
$output[] = array($itemName, $itemCat, $endDate, $auctionType, $highBidder);
}
echo json_encode($output);
$retrieve_link->close()
It looks to me like you may have some confusion about ->fetch() and ->fetch_row(). You should use one or the other, but not both.
Try this to retrieve your result set:
$stmt->execute();
while ($dataset = $stmt->fetch_row()) {
$response[] = $dataset; //returned data forms part of larger dataset
}
This will append each row of your result set to your $response array.
I created a basic form that uses jquery (ajax) to send data to php. PHP should insert a new record based on the data to a mysql database. The reason for this is because I want to make insertions to the database without having to submit the whole form and then use the submit action for something else later. It seems that the jquery works fine since the alert() shows the correct output for the variables, but the PHP does not insert the data and I don't get an error. I can't figure out why this isn't working? I think it is a problem with my $post() because the function underneath does not execute but I can't pinpoint the error. Any help debugging this would be really appreciated. Or if anyone knows another way to get the same functionality that would be great too? Thanks. (The code below works fine now. I figured out it was a type cast error, and I fixed it. Hopefully someone can find this useful!)
<script type="text/javascript">
function submitgrade(){
alert("In it");
var classID = $("#classSelect").val();
var student = $("#studentSelect").val();
var exam = $("#Exam").val();
var grade = $("#grade").val();
alert(classID+" - "+student+" - "+exam+" - "+grade);
$.post('submitgrade.php',{postclassSelect:classID,poststudentSelect:student,postExam:exam,postgrade:grade}, /*1*/
function(data){
$("#grade").html("");
});
};
</script>
<?php /*submitgrade.php*/
$con=mysqli_connect("localhost","root","","studentbase");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$classID = $_POST['postclassSelect'];
$studentID = $_POST['poststudentSelect'];
$examID = $_POST['postExam'];
$grade = $_POST['postgrade'];
echo $studentID[0]." examID: ". $examID[0];
$gradequery = "INSERT INTO grade VALUES(".intval($studentID).", '".$classID."', ".intval($examID).", ".intval($grade).");";
$result = $con->query($gradequery);
while($row = $result->fetch_assoc())
{
echo "<br /><p>Grade of ". $grade." submitted for exam ". $row['exam_id'] ." in ". $row['class_ID'] ."</p>";
}
?>
Have you include this line in your html page ??
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
An example is here again, may help you
<script>
$(document).ready(function(){
$("input").keyup(function(){
txt=$("input").val();
$.post("my_page.asp",{suggest:txt},function(result){
$("span").html(result);
});
});
});
but your code seems correct too buddy !!
I suggest to continue debugging by attaching an error handler to your $.post call, your code could look this:
$.post('submitgrade.php', {postclassSelect:classID,poststudentSelect:student,postExam:exam,postgrade:grade})
.done(function(response) {
// success
}).fail(function(response) {
// failure
});
Further more you should check:
Is the script running on a server? ajax might not work on a file:/// address
Is the path from javascript location to php file correct?
what do the browser developer tools say about the request that is initiated?
I fixed it. It was actually just a syntax error in my SQL and a type difference error with one of my database columns. The $grade variable is passed into PHP as a string. Once I wrapped all of my variables in intval() it worked as intended. Stare at the code to long, sometimes you go blind. Haha.
Thank you omnidan for the tip about sanitization. Here is a good guide that I used to apply it to my app:
http://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data