I have the following code on my PHP webapp, it uses PHP to look for products in a Sqlite3 Databse file locally. I was tryng to convert it into an Android App with Phonegap, but sadly Phonegap does't work with PHP, so I thought I could make a JavaScript file replacing the PHP.
However, I can't get it to work. In case what I am trying to do is impossible, I guess there should be a way to execute the PHP files on the server and just display the results on the app.
($_GET['busq']){
$busq=$_GET['busq'];
function ultlet($cadena) {
$cant = strlen($cadena);
$cant--;
$let = substr($cadena, $cant);
if ($let == "s") {
$cadena = substr($cadena, 0, $cant);
}
return $cadena;
}
str_replace("-",$busq," ");
$arreg=explode(" ",$busq);
$cuent=count($arreg);
for($a=0;$a<$cuent;$a++){
$arreg[$a] = ultlet($arreg[$a]);
}
$query="SELECT * from MyTable WHERE";
for($i=0;$i<$cuent;$i++){
if ($i>=1){
$query=$query." AND ";
}
$query=$query." (col1 LIKE \"%$arreg[$i]%\" OR col6 LIKE \"%$arreg[$i]%\") ";
}
$db = new PDO('sqlite:MyDatabase.sqlite');
$result = $db->query($query);
foreach ($result as $row) {
if ($row['codigo_cat']!=null){
$class = 'class="image"';
}else{
$class = 'class="row"';
}
echo '<div '.$class.' alt="'.$row['col4'].'">';
echo 'Codigo: '.$row['col2']." / ".$row['col3']."<br>";
echo 'Nombre: '.$row['col1']."<br>";
echo '</div>';
}
}
There is also another file wich based on the user's input on a search bar creates the variable 'busq' which is used to display the products and its prices.
Modify the PHP script to output its contents as an xml file, and use javascript's XMLHttpRequest function to create a request to the file, and get the information you need.
Related
I have an array in .php file and i want to pass that array to .ts file through service provider and print them using *ngFor in Ionic Angular4.
$query = mysqli_query($conn,"SELECT * FROM master_user");
$messages = array();
if ($query->num_rows > 0) {
while($message = $query->fetch_assoc()) {
$messages[] = $message;
}
}
currently i am able to pass single value by below code:
echo '{"success":{"message":"success"}}';
In .ts file i am getting this value by the following code:
"data.success.message";
Just like the above i want to pass the array value to .ts and access that array.Hope this code makes sense.Kindly help me with this
$query = mysqli_query($conn,"SELECT * FROM master_user");
$messages = array();
if ($query->num_rows > 0) {
while($message = $query->fetch_assoc()) {
$messages[] = $message;
}
}
echo JSon_encode($messages);
and in the ts file console it directly like this:
console.log(data);
after viewing data into the console you will come to know how to use it and you can iterate using *ngFor in the HTML file.
In order to return the array to you service provider you should format it to json using json_encode, if you do that you will be able to affect directly your result to your object in the front-end,
Your php code should be
echo json_encode($messages);
instead of
echo '{"success":{"message":"success"}}';
And in your service provider just retrieve the messages.
I'm in the process of doing a "mock" website for a class and I'm having issues getting the information from my database file, to the actual page in my site. I should mention that I'm a total php newb. Also there isn't any security yet.
I'm calling the connection from another file, so I didn't include that.
database function:
function GetProductsByCategory($categoryID) {
global $conn, $productsResult;
echo $categoryID;
$sql = "SELECT * FROM products WHERE prodCategory = '$categoryID'";
$productsResult = $conn->query($sql);
}
Website File:
//In the head of website file
<?php
$categoryID = "87";
if (isset($_GET['category'])) {
GetProductsByCategory($categoryID);
} else {
// Fallback behaviour goes here
}
?>
//In the body
<?php while ($row = $productsResult->fetch_assoc()) {
//Just trying to get information from the database file
echo '<div>'.$row["prodName"].'</div>';
}
?>
I should mention that nothing throws an error, It echos out the category ID at the top, but inside the <div> it just doesn't show anything.
Call the function and save the result in a variable:
$result = GetProductsByCategory($categoryID);
then inside the function:
$productsResult = $conn->query($sql);
return $productsResult;
then your while loop should use this returned result (i.e., $result):
while ($row = $result->fetch_assoc()) { ... }
I am new in this json chapter.I have a file named mysql_conn.php .This file have a php function to call data from mysql database.So can anyone help me to create one json file to get data from mysql_conn.php.Below is my code
mysql_conn.php
function getWrkNoTest($wrkno){
$conf = new BBAgentConf();
$log = new KLogger($conf->get_BBLogPath().$conf->get_BBDateLogFormat(), $conf->get_BBLogPriority() );
$connection = MySQLConnection();
$getWrkNoTest ="";
$lArrayIndex = 0;
$query = mysql_query("
SELECT
a.jobinfoid,
a.WRKNo,
a.cate,
a.det,
a.compclosed,
a.feedback,
a.infoID,
b.callerid,
b.customername
FROM bb_jmsjobinfo a
LEFT JOIN bb_customer b
ON a.customerid = b.customerid
WHERE a.WRKNo = '$wrkno';"
);
$result = mysql_query($query);
$log->LogDebug("Query[".$query."]");
while ($row = mysql_fetch_array($result)){
$getWrkNoTest = array("jobinfoid"=>$row['jobinfoid'],
"WRKNo"=>$row['WRKNo'],
"cate"=>$row['cate'],
"det"=>$row['det'],
"compclosed"=>$row['compclosed'],
"feedback"=>$row['feedback'],
"infoID"=>$row['customerid'],
"customerid"=>$row['infoID'],
"callerid"=>$row['callerid'],
"customername"=>$row['customername']);
$iList[$lArrayIndex] = $getWrkNoTest;
$lArrayIndex = $lArrayIndex + 1;
}
$QueryResult = print_r($getWrkNoTest,true);
$log->LogDebug("QueryResult[".$QueryResult."]");
closeDB($connection);
return $iList;
}
json.php
if ($_GET['action']=="getJsonjms"){
$wrkno = $_GET["wrkno"];
if($wrkno != ""){
$jms = getWrkNoTest($wrkno);
if(!empty($jms)){
echo json_encode($jms);
}else{
echo "No data.";
}
}else{
echo "Please insert wrkno";
}
}
I dont know how to solve this.Maybe use foreach or something else.Sorry for my bad english or bad explanation.I'm really new in this json things. Any help will appreciate.Thanks
If I understand your question right, you want to convert the results you receive from your MySQL query into JSON and then store that data into a file?
If this is correct, you can build off of what you currently have in json.php. In this block here, you use json_encode():
if(!empty($jms)){
echo json_encode($jms);
}
We can take this data and pass it to file_put_contents() to put it into a file:
if (!empty($jms)) {
$json = json_encode($jms);
// write the file
file_put_contents('results.json', $json);
}
If this is a script/page that's visited frequently, you'll want to make the filename (above as results.json) into something more dynamic, maybe based on the $wrkno or some other schema.
I'm an AJAX novice and I'm having major trouble trying to get data out of mySQL and into my javascript function.
What I want to do is loop through my data in php and somehow send that data into various named divs on the page.
Here's the code from my javascript page:
function loadPageContent(){
var projectID = getQuerystring('pid');
var templateID = getQuerystring('t');
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null){
alert ("Browser does not support HTTP Request")
return
}
var url="getImages.php"
url=url+"?projectID="+projectID
url=url+"&templateID="+templateID
xmlHttp.open("GET",url,true);
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
document.getElementById("statusdebug1").innerHTML=xmlHttp.responseText;
}
}
xmlHttp.send(null);
}
Here's the code for my php page:
<?php
$projectID = $_GET["projectID"];
$templateID = $_GET["templateID"];
include_once('includes/php/conn.php');
$sql ="select * FROM imageSel WHERE projectID='$projectID' AND templateName = '$templateID'";
$results=mysql_query($sql, $link);
if(!($mysql_rs = mysql_query($sql, $link)))
die("Error in executing query");
echo "<script language='JavaScript'>";
while($row =mysql_fetch_assoc($results) ){
$imageSelID = $row['imageSelID'];
$templateName = $row['templateName'];
$tNode = $row['box'];
$image = $row['image'];
$sql2 ="select * FROM products WHERE productid='$image'";
if(!($mysql_rs = mysql_query($sql2, $link)))
die("Error in executing query");
//Retrieve values
$row2 = mysql_fetch_array($mysql_rs);
$productname = $row2['productname'];
$subcategoryid = $row2['subcategoryid'];
$sql3 ="select * FROM subcategory WHERE subcategoryid='$subcategoryid'";
if(!($mysql_rs = mysql_query($sql3, $link)))
die("Error in executing query");
//Retrieve values
$row3 = mysql_fetch_array($mysql_rs);
$foldername = $row3['foldername'];
$foldername = strtolower($foldername);
$theImage = '<img src="images/lowres/' . $foldername . '/' . $productname .'" />';
echo "document.getElementById(".$tNode.").innerHTML=".$theImage.";";
}
echo "</script>";
?>
That's typically not how I would implement AJAX.
AJAX, when done correctly, should send data to the browser, then let the browser decide what to do with it.
Try using json_encode to put the data you want to send to the browser in JSON format, then on the Javascript end use a JSON library to decode the data then handle it appropriately.
Good luck!
please use this code :
xmlHttp.open("GET",url,false);
because if you are keeping its true then it will call asynchronize ajax.
Please correct if i am wrong.
You are setting the Ajax response to the innerHTML of the div. But you output javascript in your PHP (which becomes your Ajax response). Try outputting just the img tag without the javascript wrapper. Or, even just outputting "Hello world";
EDITED TO ADD: You're using javascript getElementById and innerHtml on the client side and the server side. It's redundant. You probably want to keep it on the client side, ie, your html and javascript
I was following this tutorial.
I need to use a php file's ouput in my HTML file to dynamically load images into a gallery. I call
function setOutput()
{
if (httpObject.readyState == 4)
document.getElementById('main').src = httpObject.responseText;
alert("set output: " + httpObject.responseText);
}
from
function doWork()
{
httpObject = getHTTPObject();
if (httpObject != null) {
httpObject.open("GET", "gallery.php?no=0", true);
httpObject.send(null);
httpObject.onreadystatechange = setOutput;
}
}
However, the alert returns the php file, word for word. It's probably a really stupid error, but I can't seem to find it.
The php file:
<?php
if (isset($_GET['no'])) {
$no = $_GET['no'];
if ($no <= 10 && $no >1) {
$xml = simplexml_load_file('gallery.xml');
echo "images/" . $xml->image[$no]->src;
}
else die("Number isn't between 1 and 10");
}
else die("No number set.");
?>
If the alert is returning the contents of the PHP file instead of the results of executing it, then the server is not executing it.
Test by accessing the URI directly (instead of going via JavaScript).
You probably need to configure PHP support on the server.
Your Server doesn't serve/parse PHP files! You could test your JavaScript code by setting the content of gallery.php to the HTML code you want to receive.