When i select an option I call a Javascript code with the onchange function.
I send 2 parameters with it:
//capaciteit.php
function testfunction(week, id)
{
window.location.href = "capaciteitberekening.php?week=" + week + "&id=" + id;
}
I call the file capaciteitberekening.php and send the parameters with it.
then I try to get the both parameters with the $_GET function:
//capaciteitberekening.php
require ('capaciteit.php');
$id = $_GET['id'];
$week = $_GET['week'];
echo $id, $week;
After I echo both $id and $week(to check if they are working) I call a query:
//capaciteitberekening.php
$datumbegin = mysql_query("SELECT * FROM capaciteit");
while($row = mysql_fetch_array($datumbegin))
{
echo $row['DAGEN'];
}
When I try this on my website its only shows the echo of $id and $week.
this code is working code since I use it somewhere else and it works fine there.
this is the way i connect to my DB:
require('auth.php');require_once('config.php');require_once('exec/pubs_exec.php');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD); //Database openen
if(!$link) die('Niet gelukt om verbinding te maken met de server: ' . mysql_error());
$db = mysql_select_db(DB_DATABASE); //Select database
if(!$db) die("Selecteren van DB mislukt");
in config.php i set the values for DB_host, DB_USER, DB_PASSWORD and DB_DATABASE
What am I doing wrong here?
You shouldn't use the mysql_* methods, as they have been deprecated since PHP 5.5. (A more thorough explanation of how to go from the mysql_* library to PDO).
To actually also answer your question, you probably don't have errors enabled on your website and don't see the error that occurs when the mysql connection fails (which stops execution of the PHP script at the line it occurs at)
Related
I'm building a leaflet web app which stores messages assigned to geolocations.
I add data one line at a time by sending it from javascript to PHP using:
$name = mysqli_real_escape_string($conn, $_POST['NAME']);
$latitude = mysqli_real_escape_string($conn, $_POST['LATITUDE']);
$longitude = mysqli_real_escape_string($conn, $_POST['LONGITUDE']);
$message = mysqli_real_escape_string($conn, $_POST['MESSAGE']);
$sql = "INSERT INTO geoData (NAME,LATITUDE,LONGITUDE,MESSAGE)
VALUES ('$name', '$latitude', '$longitude', '$message')";
I get the data back out using PHP to echo the data back to javascript using:
$conn = mysqli_connect($dbServername,$dbUsername, $dbPassword, $dbName);
if(! $conn ){
die('Could not connect: ' . mysqli_error());
}
$sql = 'SELECT * FROM geoData';
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
} else {
echo "0 results";
}
mysqli_close($conn);
<script type="text/javascript">
var data = JSON.parse( '<?php echo json_encode($rows); ?> ' );
</script>
This works fine UNLESS the message has special characters such as apostrophes for example 'Dave's dogs's bone'. This creates an error
What is the best practise for such an application which uses PHP and javascript. I think I need some way to encode the special characters which javascript can then decode and display.
The error comes as:
Uncaught SyntaxError: missing ) after argument list
<script type="text/javascript">
var data = JSON.parse( '[{"NAME":"The Kennel","LATITUDE":"50.7599143982","LONGITUDE":"-1.3100980520","MESSAGE","Dave's Dog's Bone"}] ' );
</script>
Many thanks
The issue is your JSON.parse() which isn't needed at all in this case.
Change:
var data = JSON.parse( '<?php echo json_encode($rows); ?> ' );
to
var data = <?= json_encode($rows); ?>;
JSON.parse() is for parsing stringified json. Echoing the result from json_encode() will give you the correct result straight away.
Side note
I would recommend adding $rows = []; before your if (mysqli_num_rows($result) > 0) or json_encode($rows) will throw an "undefined variable" if the query doesn't return any results (since that variable currently is created inside the loop when you're looping through the results).
Side note 2
When making database queries, it's recommended to use parameterized Prepared Statements instead of using mysqli_real_escape_string() for manually escaping and building your queries. Prepared statements are currently the recommended way to protect yourself against SQL injections and makes sure you don't forget or miss to escape some value.
You produce that error yourself by adding ' in json. If you want check that use this:
JSON.parse( '[{"NAME":"The Kennel","LATITUDE":"50.7599143982","LONGDITUTE":"-1.3100980520","type":"bad","reason":"Dave\'s Dog\'s Bone","improvement":"","reviewed":"0"}] ' );
And if you want correct that in main code use str.replace(/'/g, '"') for your var data, before parse it to json.
I am new to php and I am not sure how to debug this.
I am trying to pass json to a php page and then send that data to mySQL.
I think it is having issues interpreting the data inside the php file or getting the information to the php page. When I open the php file it gives signs that it is properly accessing the database.
Here is my javascript code:
var request = new XMLHttpRequest();
request.open('POST', 'http://website/saveF.php', true);
request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
request.send(bInfo);
This is taking information in and passing it to a php file to then be added to a mySQL database.
Here is my php code:
This is decoding the jSon and then itterating over each entry inside the array. It then asks the question if it has a website listed or not and stores it into the appropriate table.
//as long as the connection is good then we keep it live.
include_once "head.php";
if ($conn->connect_error) {
die("connection failed: " . $conn->connect_error);
}
//gettting the information from the front end (index.html)
$inputJSON = file_get_contents('php://input');
//decode all the previously encoded information
$postThings = json_decode($inputJSON, TRUE);
$input = filter_var($postThings, FILTER_SANITIZE_STRING);
//create a variable the is the total length of our array
$totalNum = count($input);
//arrays start at 0
$i = 0;
//you can see where this is going. We have a while loop that will continue as long as i is less than totalnum. Ask me why i didn't use a for loop.... I don't have an answer.
while($i < $totalNum){
$var0 = $input[$i][0];
$var1 = $input[$i][1];
$var2 = $input[$i][2];
$var3 = $input[$i][3];
$var4 = $input[$i][4];
$var5 = $input[$i][5];
$var6 = $input[$i][6];
if($var1 == "Not Listed") {
$sql = "INSERT INTO missing(cName, website, rating, phone, id, address, placeType) VALUES ('$var0', '$var1', '$var2', '$var3', '$var4', '$var5', '$var6')";
}else{
//here we set the information into the database.
$sql = "INSERT INTO companies(cName, website, rating, phone, id, address, placeType) VALUES ('$var0', '$var1', '$var2', '$var3', '$var4', '$var5', '$var6')";
}
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$i++;
}
First, note that this line:
$input = filter_var($postThings, FILTER_SANITIZE_STRING);
Will return FALSE if sanitization fails on any of the array elements. In your code, you should be testing if($input) immediately after the sanitization.
Furthermore, you will want to sanitize your inputs further to avoid SQL injection and XSS attacks. (e.g. remove SQL escape characters and other injectable characters).
http://php.net/manual/en/mysqli.real-escape-string.php
Last, it is recommended that you use bound parameters or fully sanitized inputs to avoid a SQL injection attack.
I am having a weird problem, I am trying to populate the datatable using ajax call to my php program which internally gets data from database.
php:
<?php
require_once('config.php');
$query = mysql_query("select * from productdetails");
while($fetch = mysql_fetch_array($query))
{
$output[] = array ($fetch[0],$fetch[1],$fetch[2],$fetch[3],$fetch[4],$fetch[5]);
}
echo json_encode($output, JSON_FORCE_OBJECT);
?>
Html(ajax call):
$.ajax({
url: 'process.php?method=fetchdata',
data: "json",
success: function(s){
console.log($(s).text());
oTable.fnClearTable();
for(var i = 0; i < s.length; i++) {
oTable.fnAddData([
s[i][0],
s[i][1],
s[i][2],
s[i][3],
s[i][4],
s[i][5]
]);
} // End For
},
error: function(e){
console.log(e.responseText);
}
});
This generates the output as
( ! ) Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in C:\wamp\www\datatableone\process.php on line 2
Call Stack
#TimeMemoryFunctionLocation
10.0010242552{main}( )..\process.php:0
20.0010242840http://www.php.net/function.mysql-connect' target='_new'>mysql_connect
( )..\process.php:2
{"0":{"0":"1","1":"Iron","2":"AX12","3":"Google","4":"21.95","5":"HW"},"1":{"0":"2","1":"DartBoard","2":"AZ52","3":"Apple","4":"12.95","5":"SG"},"2":{"0":"3","1":"BasketBall","2":"BA74","3":"Microsoft","4":"29.95","5":"SG"},"3":{"0":"4","1":"Compopper","2":"BH22","3":"Google","4":"24.95","5":"HW"},"4":{"0":"5","1":"Gas Grill","2":"BT04","3":"Apple","4":"149.95","5":"AP"},"5":{"0":"6","1":"Washer","2":"BZ66","3":"Google","4":"399.99","5":"AP"}}
But my required output should be: (only json)
{"0":{"0":"1","1":"Iron","2":"AX12","3":"Google","4":"21.95","5":"HW"},"1":{"0":"2","1":"DartBoard","2":"AZ52","3":"Apple","4":"12.95","5":"SG"},"2":{"0":"3","1":"BasketBall","2":"BA74","3":"Microsoft","4":"29.95","5":"SG"},"3":{"0":"4","1":"Compopper","2":"BH22","3":"Google","4":"24.95","5":"HW"},"4":{"0":"5","1":"Gas
Grill","2":"BT04","3":"Apple","4":"149.95","5":"AP"},"5":{"0":"6","1":"Washer","2":"BZ66","3":"Google","4":"399.99","5":"AP"}}
any suggestions please.
Thanks
Sai
Solution:
PHP:
<?php
$servername = "localhost";
$username = "root";
$password = "123456";
try {
$conn = new PDO("mysql:host=$servername;dbname=holt", $username, $password);
$statement=$conn->prepare("SELECT * FROM productdetails");
$statement->execute();
$results=$statement->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($results);
echo $json;
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
Thanks for suggestions.
As noted in the comments, you should turn off warnings, or better yet, write your code in a manner that doesn't produce warnings.
On turning off warnings:
Turn off warnings and errors on php/mysql
You can suppress errors inline with the # symbol, which is the error control operator in php. Putting # at the beginning of your mysql_connect() line should get rid of it, but you should switch to PDO!
On PDO (which I recommend and use):
http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059
PDO protects you against SQL injection and allows queries to be sent to the database and constructed beforehand, and you send the inputs afterwards via "placeholders".
I have some problems trying to redraw some markers (on google maps) from a database, use the form jquery
Index.html:
var map;
var datos;
function updateLocations(){
var post= $.post('php/getLoc.php',{table: "Auto"), function f(data){
datos =[]; //clear array with the last positions
datos = data;
drawAutos(datos); }); }
php/getLoc.php:
$link = mysql_connect("localhost","root","") or die('could not connect: '.mysql_error());
mysql_select_db("database") or die ('could not select db');
$autos= "SELECT * FROM autos ORDER BY auto_id ASC";
$result=mysql_query($autos) or die('query fail'.mysql_error());
$datos= array();
while($row= mysql_fetch_assoc($result)){
$datos[] = array(
0=>$row['taxi_id'],
1=>$row['lat'],
2=>$row['lng'],
3=>$row['availability']);}
$out = array_values($datos);
var_dump(json_encode($out));
mysql_free_result($result);
mysql_close($link);
The query is correct, but I get the information otherwise. there is a way to remove the string () "" (see picture), I have tried using $.parseJSON(data) and $.getJSON(data) but not work for me =(
echo json_encode($out); instead of var_dump($out);. Also, mysql is depreciated. Use mysqli or PDO or something else. The Object Oriented Approach will save you time. Also, you can $mysqli_result->fetch_all(MYSQLI_ASSOC) instead of making your while loop.
Ok, is working now :), thanks to PHPglue, I use
PHP File:
echo json_encode($out)
I also do in Index File:
var obj = $.parseJSON(data);
drawAutos(obj);
I'm using "Bootstrap Editable" with "in line editing".
I'm printing a table with data from MySQL.
Now i´d like to be able to edit a cell and update my database with PHP.
The "in line edit" script works fine.
But the mysql update doesn't.
Now, when i turn on "php error mode" or tries to "JS alert" my variables in post php, to check if they holds data i can't see any errors or alerts on the front page.
How can i read the error codes or alerts?
This is my code:
HTML
echo "<td><a href='#' id='element_ant' data-type='text' data-pk='".$row['id']."' data-url='php/posts.php' data-title='Anteckning..'>".$row['element_ant']."</a></td>";
PHP
if($_POST['name']=='element_ant'){
$id=$_POST['pk'];
$element_ant=$_POST['value'];
//Prepare query
$query = "SELECT COUNT(*) as count FROM table WHERE id=$id";
try{
$stmt = $db->prepare($query);
$result = $stmt->execute();
}
catch(PDOException $ex){
die("Failed to run query: " . $ex->getMessage());
}
//Result from query
$row = $stmt->fetch();
//Deside insert or update
if($row[0]==0){
$query = "INSERT INTO table(id,element_ant) VALUES(:id,:element_ant)";
}
else{
$query = "UPDATE table SET element_ant = :element_ant WHERE id = :id";
}
// Security measures
$query_params = array(':id' => $id,':element_ant' => $element_ant);
//Connect and execute
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex){
die("Failed to run query: " . $ex->getMessage());
}
}
JS
$(document).ready( function () {
$('#element_ant').editable({
url : '../php/elements.php',
title : 'Enter comments'
});
});
1) The url attribute is duplicated, i.e you have declared it as data-url in your HTML and in your Js code as url:. Decide which one is right and use either, not both.
2) In your php, there is if($_POST['name']=='element_ant'); you have to set it in your editable HTML element as such:
<a href='#' id='element_ant' data-name="element_ant"
When the Editable object is being saved, the data-name will be passed as a POST parameter name.
For Client-Side Debugging: Firebug
For Server-Side Debugging: Xdebug
I think you can use some sort of logging framework , or you can write your own logging functions to log your error code on the file system.