Autoselect and jQuery post doesnt work together - php

I have another problem with my code.
<script type="text/javascript">
$("#wojewodz").change(function(){
var id_wojewodztwa = $("#wojewodz").children(":selected").attr("id");
$.post("miasta.php", { id_wojewodztwa: id_wojewodztwa } );
$('#powiat_miasto_auto_complete').autocomplete({source:'miasta.php', minLength:2});
});
</script>
this is functions which get ID of selected select and transfering it to miasta.php
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
try {
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass, $options);
}
catch(PDOException $e) {
echo $e->getMessage();
}
$return_arr = array();
if (($conn) and (isset($_GET['id_wojewodztwa'])))
{
$id_wojewodztwa = $_GET['id_wojewodztwa'];
$ac_term = "%".$_GET['term']."%";
$query = "SELECT DISTINCT nazwa FROM podzial_tm where woj='$id_wojewodztwa' and nazdod!='województwo' and nazwa like :term LIMIT 10";
$result = $conn->prepare($query);
$result->bindValue(":term",$ac_term);
$result->execute();
/* Retrieve and store in array the results of the query.*/
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$row_array['value'] = $row['nazwa'];
array_push($return_arr,$row_array);
}
}
/* Free connection resources. */
$conn = null;
/* Toss back results as json encoded array. */
echo json_encode($return_arr);
?>
somebody can tell me where is some mistake?
when i change " where woj='$id_wojewodztwa'" to for example " where woj='26'" and delete " and (isset($_GET['id_wojewodztwa']))" everything is ok, so i think i have problem with POST
happy Easter! :)))

You are POSTing the data. You need to look in $_POST['id_wojewodztwa'] for the value you are looking for, not in $_GET.

$.post("miasta.php", { id_wojewodztwa: id_wojewodztwa } );
to
$.get("miasta.php", { id_wojewodztwa: id_wojewodztwa } );
or if you have to catch up the result, use:
$.get("miasta.php", { id_wojewodztwa: id_wojewodztwa },function(result){
/** some code here */
},'json');
UPDATE:
if you use $.post, edit the following lines:
if (($conn) and (isset($_POST['id_wojewodztwa'])))
{
$id_wojewodztwa = $_POST['id_wojewodztwa'];

Remove isset($_GET['id_wojewodztwa']) and also modify $id_wojewodztwa = intval($_GET['id_wojewodztwa']);

Related

Insert Base64 Images to Array PHP PDO

I'm trying to insert Blob images retrieved from MySQL into an array using a while loop.
The database statement selected all images then i need to pass them all into an array.
So in theory, i should have an array of base64 encoded image corresponding to each record from my database.
Any help will be appreciated.
$sql = "SELECT img from artistlocation";
try{
$db = new db();
$db = $db->connect();
$stmt = $db->query($sql);
$data = array();
while($result = $stmt->fetch(PDO::FETCH_OBJ))
{
//$result = base64_encode(); ---- Something here im guessing
$data[] = $result;
}
print_r ($data);
}
catch(PDOException $e){
echo '{"error": {"text": '.$e->getMessage().'}';
}
I see big issue i your code..
You use the same variable, $result, for fetching mysql row result and image content.
Second, you miss to encoding to base64 the file content.
Here is my solution:
$sql = "SELECT img from artistlocation";
try{
$db = new db();
$db = $db->connect();
$stmt = $db->query($sql);
$data = array();
while($result = $stmt->fetch(PDO::FETCH_OBJ))
{
$data[] = base64_encode($result['img']);
}
print_r ($data);
}
catch(PDOException $e){
echo '{"error": {"text": '.$e->getMessage().'}';
}
Hope it will helps you.
So the answer to this question came from AbraCadaver.
$sql = "SELECT img from artistlocation";
try{
$db = new db();
$db = $db->connect();
$stmt = $db->query($sql);
$data = array();
while($result = $stmt->fetch(PDO::FETCH_OBJ))
{
$data[] = base64_encode($result->img);
}
Thanks guys for the help!

reading entries from database

is anyone able to find out what went wrong in this code below? It just shows a blank page. I'm new to PDO, always used mysqli but someone told me to try PDO since my page had problems showing arabic characters.
<html>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<?php
/* Connect to an ODBC database using driver invocation */
$dsn = 'mysql:dbname=testdb;host=127.0.0.1;charset=UTF8;'
$user = 'dbuser'; // don't hardcode this...store it elsewhere
$password = 'dbpass'; // this too...
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$sql = "SELECT :column FROM :table";
$opts = array(
':column' => 'Name',
':table' => 'Mothakirat'
);
$dbh->beginTransaction();
$statement = $dbh->prepare($sql);
if ($statement->execute($opts)) {
$resultArray = array(); // If so, then create a results array and a temporary one
$tempArray = array(); // to hold the data
while ($row = $result->fetch_assoc()) // Loop through each row in the result set
{
$tempArray = $row; // Add each row into our results array
array_push($resultArray, $tempArray);
}
echo json_encode($resultArray); // Finally, encode the array to JSON and output the results
}
$dbh->commit();
</html>
This has no parse errors checked in my IDE. I use netbeans, its very good and available on several platforms.
<html>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<?php
/* Connect to an ODBC database using driver invocation */
$dsn = 'mysql:dbname=testdb;host=127.0.0.1;charset=UTF8;';
$user = 'dbuser'; // don't hardcode this...store it elsewhere
$password = 'dbpass'; // this too...
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$sql = "SELECT :column FROM :table";
$opts = array(
':column' => 'Name',
':table' => 'Mothakirat'
);
$dbh->beginTransaction();
$statement = $dbh->prepare($sql);
if ($statement->execute($opts)) {
$resultArray = array(); // If so, then create a results array and a temporary one
$tempArray = array(); // to hold the data
while ($row = $result->fetch_assoc()) // Loop through each row in the result set
{
$tempArray = $row; // Add each row into our results array
array_push($resultArray, $tempArray);
}
echo json_encode($resultArray); // Finally, encode the array to JSON and output the results
}
$dbh->commit();
?>
</html>

Getting MSSQL Stored Proc Results with PHP PDO

I have a reasonably complicated stored procedure in MSSQL 2008 R2 that, in the end, results in a small table being returned. The PHP will be called from javascript and I want it to return the array as JSON to be used in table in the javascript.
I am using PHP to access it and, using the profiler, can see that I am calling the SP and passing the correct parameters to it.
My PHP looks like this:
try {
$dbh = new PDO("sqlsrv:Server=(local);Database=cddDispo");
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo json_encode("Error connecting to the server.");
die ();
}
$lot = $_POST["lot-input"];
$layerAdder = $_POST["layer-input"];
$adder = substr($layerAdder,-3,3);
$adder = str_replace('=','',$adder);
$layer = substr($layerAdder,0,strpos($layerAdder,' '));
$sth = $dbh->prepare('EXEC dbo.pullDispo ?,?,?');
$sth->bindParam(1,$lot,PDO::PARAM_STR);
$sth->bindParam(2,$layer,PDO::PARAM_STR);
$sth->bindParam(3,$adder,PDO::PARAM_STR);
$array = array();
try {
$sth->execute();
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
//I want to build my output array here
}
}catch (PDOException $e) {
echo "Error getting data, please try again.";
die();
}
header('Content-type: application/json');
echo json_encode($array);
This is the first time that I have tried to return table results from a stored procedure and even with several PHP Manual/ Google searches I have not figured out how to capture the table back in the PHP. I have a less elegant workaround (write the SP table to a static table and call that table later in the PHP) but would rather figure out if I can do in a more elegant manner. Any advice is much appreciated.
I thought it might be useful if I posted my final code:
function array_push_assoc($array,$key,$value) {
$array[$key] = $value;
return $array;
}
header('Content-type: application/json');
try {
$dbh = new PDO('sqlsrv:Server=(local);Database=cddDispo');
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo json_encode('Error connecting to the server.');
die ();
}
$lot = $_POST['lot'];
$layer = $_POST['layer'];
$adder = $_POST['adder'];
$sth = $dbh->prepare('EXEC dbo.pullDispo ?,?,?');
$sth->bindParam(1,$lot,PDO::PARAM_STR);
$sth->bindParam(2,$layer,PDO::PARAM_STR);
$sth->bindParam(3,$adder,PDO::PARAM_STR);
$results = array();
$combinedArray = array();
$array = array();
$count = 0;
try {
$sth->execute();
do {
$results[] = $sth->fetchAll(PDO::FETCH_ASSOC);
}while ($sth->nextRowset());
foreach($results as $row) {
if($count == 0) {
$headerArray =
[
'Lot' =>$row['Lot'],
'Layer' =>$row['Measured Layer'],
'Product' =>$row['MES Product'],
'Adder' =>$row['Adder Chart']
];
$combinedArray = array_push_assoc($combinedArray,'header',$headerArray);
}
$count++;
//This is for formatting of final table
if($row['UDL'] == 0) {
$udl = 'NA';
} else {
$udl = round($row['UDL'],4);
}
$infoArray =
[
'Wafer' =>$row['Wafer'],
'Type' =>$row['Type'],
'Count' =>$row['Count'],
'CDD' =>round($row['CDD'],3),
'UCL' =>round($row['UCL'],4)
];
array_push($array,$infoArray);
}
$combinedArray = array_push_assoc($combinedArray,'detail',$array);
}catch (PDOException $e) {
echo json_encode('Error running stored procedure.');
die();
}
echo json_encode($combinedArray);
Could it be that your stored procedure is returning multiple result sets? This includes output like warning messages or number of rows affected. Try adding SET ANSI_WARNINGS OFF or SET NOCOUNT ON at the top of your stored procedures after the AS. You can also try advancing to the next result set in PHP before trying to get the results by calling $stg->nextRowset() before $sth->fetchAll().
Use fetchAll() to get your resultset, then encode that array as your json response:
$array = array();
try {
if($sth->execute()){
$array = $sth->fetchAll(PDO::FETCH_ASSOC);
}else{
$array = array('error'=>'failed to execute()')
}
}catch (PDOException $e) {
echo "Error getting data, please try again.";
die();
}
header('Content-type: application/json');
echo json_encode($array);
When you are calling a stored procedure with multiple result sets, you probably do not want to add SET NOCOUNT ON into every procedure you have; you always can add
$dbh->setAttribute(constant('PDO::SQLSRV_ATTR_DIRECT_QUERY'), true);
$dbh->query("SET NOCOUNT ON");
before of
$dbh->prepare($query);
and it will work.

returning multiple rows from mysql in php

I'm trying to write a PHP-script that will fetch multiple rows from MySQL and return them as a JSONObject, the code works if I try to only fetch 1 row but if I try to get more than one at a time the return string is empty.
$i = mysql_query("select * from database where id = '$v1'", $con);
$temp = 2;
while($row = mysql_fetch_assoc($i)) {
$r[$temp] = $row;
//$temp = $temp +1;
}
If I write the code like this it returns what I expect it to, but if I remove the // from the second row in the while loop it will return nothing. Can anyone explain why this is and what I should do to solve it?
You are using an obsolete mysql_* library.
You are SQL injection prone.
Your code is silly and makes no sense.
If you really wan to stick to it, why simply not do:
while($row = mysql_fetch_assoc($i)) {
$r[] = $row;
}
echo json_encode($r);
And finally, an example using PDO:
$database = 'your_database';
$user = 'your_db_user';
$pass = 'your_db_pass';
$pdo = new \PDO('mysql:host=localhost;dbname='. $database, $user, $pass);
$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
try
{
$stmt = $pdo->prepare("SELECT * FROM your_table WHERE id = :id");
$stmt->bindValue(':id', $id);
$stmt->execute();
$results = $stmt->fetchAll(\PDO::FETCH_ASSOC);
}
catch(\PDOException $e)
{
$results = ['error' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine());
}
echo json_encode($results);
You don't need the $temp variable. You can add an element to an array with:
$r[] = $row;

Run a call from a function PHP

i'm building an website using php and html, im used to receiving data from a database, aka Dynamic Website, i've build an CMS for my own use.
Im trying to "simplify" the receiving process using php and functions.
My Functions.php looks like this:
function get_db($row){
$dsn = "mysql:host=".$GLOBALS["db_host"].";dbname=".$GLOBALS["db_name"];
$dsn = $GLOBALS["dsn"];
try {
$pdo = new PDO($dsn, $GLOBALS["db_user"], $GLOBALS["db_pasw"]);
$stmt = $pdo->prepare("SELECT * FROM lp_sessions");
$stmt->execute();
$row = $stmt->fetchAll();
foreach ($row as $row) {
echo $row['session_id'] . ", ";
}
}
catch(PDOException $e) {
die("Could not connect to the database\n");
}
}
Where i will get the rows content like this: $row['row'];
I'm trying to call it like this:
the snippet below is from the index.php
echo get_db($row['session_id']); // Line 22
just to show whats in all the rows.
When i run that code snippet i get the error:
Notice: Undefined variable: row in C:\wamp\www\Wordpress ish\index.php
on line 22
I'm also using PDO just so you would know :)
Any help is much appreciated!
Regards
Stian
EDIT: Updated functions.php
function get_db(){
$dsn = "mysql:host=".$GLOBALS["db_host"].";dbname=".$GLOBALS["db_name"];
$dsn = $GLOBALS["dsn"];
try {
$pdo = new PDO($dsn, $GLOBALS["db_user"], $GLOBALS["db_pasw"]);
$stmt = $pdo->prepare("SELECT * FROM lp_sessions");
$stmt->execute();
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
echo $row['session_id'] . ", ";
}
}
catch(PDOException $e) {
die("Could not connect to the database\n");
}
}
Instead of echoing the values from the DB, the function should return them as a string.
function get_db(){
$dsn = "mysql:host=".$GLOBALS["db_host"].";dbname=".$GLOBALS["db_name"];
$dsn = $GLOBALS["dsn"];
$result = '';
try {
$pdo = new PDO($dsn, $GLOBALS["db_user"], $GLOBALS["db_pasw"]);
$stmt = $pdo->prepare("SELECT * FROM lp_sessions");
$stmt->execute();
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
$result .= $row['session_id'] . ", ";
}
}
catch(PDOException $e) {
die("Could not connect to the database\n");
}
return $result;
}
Then call it as:
echo get_db();
Another option would be for the function to return the session IDs as an array:
function get_db(){
$dsn = "mysql:host=".$GLOBALS["db_host"].";dbname=".$GLOBALS["db_name"];
$dsn = $GLOBALS["dsn"];
$result = array();
try {
$pdo = new PDO($dsn, $GLOBALS["db_user"], $GLOBALS["db_pasw"]);
$stmt = $pdo->prepare("SELECT * FROM lp_sessions");
$stmt->execute();
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
$result[] = $row['session_id'];
}
}
catch(PDOException $e) {
die("Could not connect to the database\n");
}
return $result;
}
Then you would use it as:
$sessions = get_db(); // $sessions is an array
and the caller can then make use of the values in the array, perhaps using them as the key in some other calls instead of just printing them.
As antoox said, but a complete changeset; change row to rows in two places:
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
echo $row['session_id'] . ", ";
}
Putting this at the start of the script after <?php line will output interesting warnings:
error_reporting(E_ALL|E_NOTICE);
To output only one row, suppose the database table has a field named id and you want to fetch row with id=1234:
$stmt = $pdo->prepare("SELECT * FROM lp_sessions WHERE id=?");
$stmt->bindValue(1, "1234", PDO::PARAM_STR);
I chose PDO::PARAM_STR because it will work with both strings and integers.

Categories