How to update PSQL database when array is Javascript is updated? - php

I am trying to combine PHP and Javascript, so that I get my data from the db in psql. So far, I am able to obtain the column I need, and set an array equal to this data. And then I am equating a js array to this array. This can be seen in the following code:
<?php
// attempt a connection
$dbh = pg_connect("host=localhost dbname=db user=postgres");
if (!$dbh) {
die("Error in connection: " . pg_last_error());
}
// execute query
$sql = "SELECT * FROM dataset";
$result = pg_query($dbh, $sql);
if (!$result) {
die("Error in SQL query: " . pg_last_error());
}
$arr = pg_fetch_all_columns($result, 1);
pg_free_result($result);
// close connection
pg_close($dbh);
?>
And here's the js part.
var data = <?php echo json_encode($arr); ?>;
I have a function, which adds a data point to the array. I can add it to "data" array in js, but how do I make it so that it reflects in the db?
Thanks in advance :)

Related

PHP: json_encode() doesn't show anything with multidimensional array

I'm trying to make a simple PHP script that fetches a table from my MySQL database and encodes the results in JSON, so I can use them later in Java.
This is my code:
<?php
$servername = "localhost:3036";
$username = "example_user";
$password = "example_password";
$conn = mysql_connect($servername, $username, $password);
if(! $conn) {
die("Could not connect: " . mysql_error());
}
$sql = "SELECT * FROM table_name";
mysql_select_db("database_name");
$retval = mysql_query($sql, $conn);
if(! $retval) {
die("Could not get data: " . mysql_error());
}
while($row = mysql_fetch_assoc($retval)) {
$output[]=$row;
}
print(json_encode($output));
mysql_close($conn);
?>
This just gives a blank page as output (error messages are set to display).
However, if I change json_encode($output) to json_encode($output[0]) (or any other number within the array's bounds), the output becomes that one $row array.
This is probably a really stupid question, but after about 3 hours of research I'm at my wit's end. Thank you for any help.
User #Joni led me to the solution.
Adding mysql_set_charset("utf8") fixed my issue.
As mentioned in this post: Why is this PHP call to json_encode silently failing - inability to handle single quotes?.
Try
echo json_encode($output) ;
It seems you have some utf8 character in your result set
add this statement before running your query
mysql_query('SET CHARACTER SET utf8');
Update
"mysql"
to
"mysqli"
and add
mysqli_set_charset($variável_de _conexão, 'utf8');
below the connection variable

Using PHP to output JSON data, and I get "white screen of death" when too many rows being called

I'm using PHP files to output JSON data from a MySQL database. My code works just fine when I'm only pulling about 50 rows, however my database contains over 12,000 rows. Does anyone know how I might go about pulling more data without my server returning the "White screen of death"? Lol. My current code is below:
<?php
//Create Database connection
$db = mysql_connect("localhost","username","password");
if (!$db) {
die('Could not connect to db: ' . mysql_error());
}
//Select the Database
mysql_select_db("dbname",$db);
//Replace * in the query with the column names.
$result = mysql_query("select * from customer limit 50", $db);
//Create an array
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['customerfname'] = $row['customerfname'];
$row_array['customerlname'] = $row['customerlname'];
$row_array['customeremail'] = $row['customeremail'];
$row_array['customerphone'] = $row['customerphone'];
$row_array['customercity'] = $row['customercity'];
$row_array['customeraddress'] = $row['customeraddress'];
$row_array['lastupdate'] = $row['lastupdate'];
//push the values in the array
array_push($json_response,$row_array);
}
echo json_encode($json_response);
//Close the database connection
fclose($db);
?>
If the first 50 rows are coming well, the problem is probably with the data...
i think a malicious single quote or something
You can try different sets of data by using limit like so.
for example if you want to check next 50 and skip first 50 with limit
$result = mysql_query("select * from customer limit 50, 50", $db);
i think you should try in sets of 1 to 50 , 50 to 100 and then narrow down to next 10 and find out which set and then which row / record is giving problem and then search out a solution for json encoding the problem area.
You could output json data according to GET/POST parameter, by paginating the results in your sql table. E.g., if you want the rows from 50th to 100th, you could do something like this:
<?php
//Create Database connection
$mysqli = new mysqli("localhost", "username", "password", "dbname");
if ($mysqli->connect_errno) {
die('Could not connect to db: ' . $mysqli->connect_error);
}
// Get the page we are interested in
$page = $_REQUEST['page']; // E.g. 1
//Replace * in the query with the column names.
$result = $mysqli->query("SELECT * FROM customer LIMIT ".(50*$page).",50");
//Create an array
$json_response = array();
while ($row = $result->fetch_assoc()) {
//push the values in the array
array_push($json_response,$row);
}
echo json_encode($json_response);
// free result set
$result->close();
//Close the database connection
$mysqli->close();
?>

Error calling MySQL stored procedure through PHP

I'm trying to call a stored procedure from MySQL and get back the two OUT parameters (#eset and #leng). I would like to echo out these two parameters back to JavaScript where I have an XMLHttpRequest waiting for the results.
I'm getting this error :
Strict standards: mysqli::next_result(): There is no next result set.
Here's my code:
<?php
//get the q parameter from URL
$q=$_GET["q"];
$eset= "";
$length= 0;
// Opens a connection to a MySQL server
$db= new mysqli('localhost', 'db_name', 'pass');
if (!$db) { die('Not connected : ' . mysql_error());}
// Set the active MySQL database
$db_selected = $db->select_db('db_name');
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// Select all the rows in the markers table
$db->multi_query( "CALL mst2($q, #eset, #leng);SELECT #eset as eset;SELECT #leng as length" );
$db->next_result(); // flush the null RS from the call
$eset=$db->store_result(); // get the RS containing the id
//echo $eset->fetch_object()->eset, "\n";
$length= $db->store_result();
//echo $length->fetch_object()->leng, "\n";
$response= $eset.$length;
//$eset->free();
//$length->free();
//$response=str_shuffle($q);
//output the response
echo $response;
?>
I'm assuming the first argument of your stored procedure is VARCHAR, so the first problem is that you are passing the $q variable without quotes in the query. It should be like this:
$db->multi_query("CALL mst2('$q', #eset, #leng); SELECT #eset as eset; SELECT #leng as length");
Also, you don't need to make two SELECT calls, do it only once:
SELECT #eset AS eset, #leng AS leng;
Needless to say that user inputs should never be trusted. You should use prepared statements:
if (($stmt = $db->prepare("CALL mst2(?, #eset, #leng)"))) {
$stmt->bind_param("s", $q);
$stmt->execute();
$stmt->close();
if (($res = $db->query("SELECT #eset AS eset, #leng AS leng"))) {
list($eset, $leng) = $res->fetch_array();
$result = $eset.$length;
echo $result;
$res->free();
}
}

INSERT IGNORE In mySQL

I wonder whether someone can help me please.
I'm trying to put together a PHP script that takes data from an xml file and places the data in a mySQL data. I've been working on this for a few days and I'm still can't seem to get this right.
This is the code that I've managed to put together:
<?
$objDOM = new DOMDocument();
$objDOM->load("xmlfile.xml");
$Details = $objDOM->getElementsByTagName("Details");
foreach( $Details as $value )
{
$listentry = $value->getElementsByTagName("listentry");
$listentrys = $listentry->item(0)->nodeValue;
$sitetype = $value->getElementsByTagName("sitetype");
$sitetypes = $sitetype->item(0)->nodeValue;
$sitedescription = $value->getElementsByTagName("sitedescription");
$sitedescriptions = $sitedescription->item(0)->nodeValue;
$siteosgb36lat = $value->getElementsByTagName("siteosgb36lat");
$siteosgb36lats = $siteosgb36lat->item(0)->nodeValue;
$siteosgb36lon = $value->getElementsByTagName("siteosgb36lon");
$siteosgb36lons = $siteosgb36lon->item(0)->nodeValue;
//echo "$listentrys :: $sitetypes :: $sitedescriptions :: $siteosgb36lats :: $siteosgb36lons <br>";
}
require("phpfile.php");
//Opens a connection to a MySQL server
$connection = mysql_connect ("hostname", $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
mysql_query("INSERT IGNORE INTO scheduledsites (listentry, sitetype, sitedescription, siteosgb36lat, siteosgb36lon) VALUES('$listentrys','$sitetypes','$sitedescriptions','$siteosgb36lats','$siteosgb36lons') ")
or die(mysql_error());
echo "Data Inserted!";
?>
I can pull the data from the xml file, but it's the part of the script that sends the data to my database table that I'm having trouble with.
The script runs but only the last record is saved to the database.
I can parse the fields from the xml file without any problems and the check I'm trying to put in place is, if there is a 'listentry' number in the new data that is matched to one already in the table then I don't want that record to be added to the table, i.e. ignore it.
I just wondered whether someone could perhaps take a look at this please and let me know where I'm going wrong.
Many thanks
You are only calling mysql_query once. So it will only insert one row.
The sql needs to be inside the loop.

php mysql connection does not show results why

this is driving me crazy why aren't the results showing???
function runSQL($rsql) {
$connect = mysql_connect('localhost','xxx','xxx') or die ("Error: could not connect to database");
$db = mysql_select_db('xxx');
$result = mysql_query($rsql) or die ("Error in query: $query. " . mysql_error());
return $result;
mysql_close($connect);
}
$rsql = "SELECT * FROM subscriptions WHERE subscriptionID = 6 ";
runSQL($rsql);
$row = mysql_fetch_array($result);
echo $row['subscription'];
mysql_free_result($result);
You don't process your result ...
You call your function (runSQL) to execute the query and it returns the resultset, but you don't catch the resultset to work with it.
Use $result = runSQL($rsql); instead of runSQL($rsql);.
Also note that mysql_close($connect); is never called in your code, it's unreachable as the return occurs first.
If you close the connection before doing mysql_fetch_(assoc|array|etc) on it, those functions will likely fail. The connection should not be closed until you're done interacting with the database, including reading the data.

Categories