Hi I'm a novice PHP developer to say the least and I'm pretty stuck.
I'm trying to get the below code working I know I need a foreach loop or similar but I'm way out of my depth, I'm really not sure how to get this working, I know to most of you this is basic stuff but I'm lost.
Basically this is a receipt when a tab is settled. It searches the MySql Database for the relevant items and should print them on the receipt.
I know the MySql Query is not linked to the output at the bottom but I don't know how to do it.
<html lang="en">
<head>
<title>Receipt</title>
</head>
<body>
<?php
$invoicenum = $_POST['invoicenum'];
$name = $_POST['name'];
$netrev=$invoicenum - 1;
?>
Items:
<?
$itemQuery = mysql_query("SELECT * FROM sales WHERE invoicenum = '$netrev' AND tabname = '$name'");
$result = array();
while($row = mysql_fetch_array($itemQuery))
{
$result[] = $row['itemname'];
}
echo json_encode($result);
$amounts = json_decode($result['amounts']);
$items = json_decode($result['items']);
$prices = json_decode($result['prices']);
?>
<br>
<?
for ($i = 0; $i < count($items); $i++)
{
echo $amounts[$i] . "x " . $items[$i] . " - " . $prices[$i] . "<br>";
}
?>
</body>
</html>
I've removed code that isn't relevant to this array, if you can help I'd be forever grateful.
no need of encode and decode.
$itemQuery = mysql_query("SELECT * FROM sales WHERE invoicenum = '$netrev' AND tabname = '$name'");
while($row = mysql_fetch_array($itemQuery))
{
echo $row['amounts'] . "x " . $row['items'] . " - " . $row['prices'] . "<br>";
}
?>
Forget all json_decode/encode after filling $result then:
First do:
$result[] = $row;
Then:
foreach ($result as $set){
echo $set['amount'] . "x " . $set['itemname'] . " - " . $set['price'] . "<br>";
#do var_dump($set); here for checking the keys
}
Related
After sending the country name "US" in JavaScript to PHP code, I will try to receive the results of PHP's work back to JavaScript and use them.
To do this I used the below code.
$ctryNm_php_temp = "document.write(ctryNm);";
As a result, it seemed that the value 'US' of the ctryNm variable was well transfered to php code.
The cryNm value and $SQL value printed on the screen contain 'US'.
However, the results of the SQL query were returned to an empty value, so we checked.
The IF statement shows that ctryNm and 'US' are different values.
(The output on the screen shows the same value and data type as string.)
I printed $result_obj and found no value.
echo and console.log command result for checking:
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script type="text/javascript">
var ctryNm = "US";
</script>
<?php
$ctryNm_php_temp = "<script language='javascript'>document.write(ctryNm);</script>";
$ctryNm_php = $ctryNm_php_temp;
echo $ctryNm_php . "<br><br>";
echo "--------------" . "<br>";
echo gettype($ctryNm_php) . "<br>";
if ($ctryNm_php == 'US') {
echo "Same" . "<br>";
} elseif ($ctryNm_php != 'US') {
echo "Different" . "<br>";
}
$conn = new mysqli("...", "...", "...");
mysqli_select_db($conn, '...');
mysqli_query($conn, "set names utf8");
$sql = "SELECT * FROM acst_covid_who WHERE country_code = '$ctryNm_php'";
echo $sql . "<br>";
$result_obj = mysqli_query($conn, $sql);
echo "result_obj :" . $result_obj . "<br>";
$date_adjust = 0;
$latestDate_trend = '';
while ($row = mysqli_fetch_array($result_obj)) {
if ((int)$row['confirmed_new'] !== 0) {
$latestDate_trend = $row['date'];
$date_adjust = 1;
} elseif ((int)$row['confirmed_new'] === 0) {
$latestDate_yester_trend = strtotime($row['date'] . "-1 days");
$latestDate_trend = date("Y-m-d", $latestDate_yester_trend);
$date_adjust = 0;
};
};
$result_obj = mysqli_query($conn, $sql);
$total_rows_trend = mysqli_num_rows($result_obj) - $date_adjust;
$arr_trend = array();
while ($row = mysqli_fetch_array($result_obj)) {
array_push($arr_trend, $row);
}
echo $total_rows_trend;
echo json_encode($latestDate_trend);
?>
<script>
var latestDate_js_trend = <?php echo json_encode($latestDate_trend) ?>;
var arr_js_trend = <?php echo json_encode($arr_trend) ?>;
var arr_length_trend = <?php echo $total_rows_trend ?>;
console.log(latestDate_js_trend);
console.log(arr_js_trend);
console.log(arr_length_trend);
</script>
</body>
</html>
this sadly does not work like this.
PHP code is executed first on the server, so before the website is even shown in the browser. The order you write it does not matter.
The process is like this:
You type the address in the browser and it asks the server for the page.
The server literally runs an app called php, that reads what you wrote in the code, reads only what is between <?php and ?>, nothing else (technically the first one can be <?=)
When it is done, the server sends the page to browser
The browser reads html and fires JavaScript, long after PHP was already changed.
This is simplified but show why your code will not work.
I'm following a tutorial (http://www.pontikis.net/blog/jquery-ui-autocomplete-step-by-step) and I try to do this but with a local phpmyadmin database, using Xampp installed on my PC.
I have a table called cars with the columns id and name, I filled in 2 entries, however, the autocomplete doesn't work, in fact, I don't get any suggestions below my form. Since I can't bother you with all the JS files, maybe someone can explain what this precisely does, especially the last while function, because I think here lies the problem:
$sql = 'SELECT id, name FROM cars';
for($i = 0; $i < $p; $i++) {
$sql .= ' AND name LIKE ' . "'%" . $conn->real_escape_string($parts[$i]) . "%'";
}
while($row = $rs->fetch_assoc()) {
$a_json_row["id"] = $row['id'];
$a_json_row["value"] = $row['name'];
$a_json_row["label"] = $row['name'];
array_push($a_json, $a_json_row);
}
You are not declaring WHERE in your SQL statement. Query likely failing, yielding zero autocomplete options.
$sql = 'SELECT id, name FROM cars';
for($i = 0; $i < $p; $i++) {
if ($i == 0){ $sql.= " WHERE"; } // THIS LINE HERE
$sql .= ' AND name LIKE ' . "'%" . $conn->real_escape_string($parts[$i]) . "%'";
}
My Solution to this Problem:
while($cars=mysql_fetch_array($query)){
$json[]=array(
'value'=>$cars["name"],
'label'=>$cars["name"]
);
}
echo json_encode($json);
I'm working on a cross-platform application and I got some troubles with my data.
Actually I have a full website with a lot of php and I'm working with the Intel XDK to make a native application of this website.
But here is the thing, I know I can execute php on my native app, so i'm trying to execute few scripts directly on my server and to take back the result with an ajax request.
Here is the code : (Javascript)
var games = location.search;
var res = games.split("=");
$.ajax({ //create an ajax request to a page that prints the address.
url: "http://tonight-app.fr/php/mobile_app/getGamesLists.php", //url for the address page
data: {"name": res[1]},
success: function(result){
var games = result; //create a variable and give it the value of the response data
var gamesSplit = games.split(";");
for(i=0;i<gamesSplit.length;i++){
var gamesSplit2 = gamesSplit[i].split(",");
test(gamesSplit2[0]);
}
}
});
function test(gamesSplit2) {
console.log(gamesSplit2);
var ul = document.createElement("ul");
ul.id = "email-list";
ul.innerHTML = gamesSplit2;
document.getElementById('test').appendChild(ul);
}
Here is the php on the server (to this address mention in the url of the ajax)
<?php
require_once("connect_database.php");
mysqli_set_charset($con, "utf8");
$name = $_GET["name"];
$sql="SELECT * FROM `games`";
$reponse = mysqli_query($con, $sql);
while ($row = mysqli_fetch_array($reponse, MYSQL_NUM)) {
if ($row[2] == $name) {
echo $result = '
<a href="gamesReceipes.php?id=',$row[0],'">
<li class="unread clickable-row">
<div class="name">
',$row[1],'
</div>
<div class="message">
Voir la préparation
</div>
</li>;';
}
}
echo $result;
?>
So to explain, I'm executing my php script which gave me the $result and i'm supposed to display this result in my Ajax.
It's working on the emulator in the Intel XDK but not after when i'm building the app ! (Of course my phone have the 4g activated)
It's supposed to be like this on the display :
[
I hope you can understand my problem here ... Thanks guys !
By this link :
https://software.intel.com/en-us/articles/cordova-whitelisting-with-intel-xdk-for-ajax-and-launching-external-apps
Thanks yo #OldGeeksGuide who gave me this link ! I just had to add the link to my script in the intel xdk and it worked ! Thanks !
You appear to be trying to echo the same thing twice. returning data to an AJAX call should be done once and the last thing you do in the script.
<?php
require_once("connect_database.php");
mysqli_set_charset($con, "utf8");
$name = $_GET["name"];
$sql="SELECT * FROM `games`";
$reponse = mysqli_query($con, $sql);
// init the $result var
$result = '';
// incorrect parameter constant
//while ($row = mysqli_fetch_array($reponse, MYSQL_NUM)) {
while ($row = mysqli_fetch_array($reponse, MYSQLI_NUM)) {
if ($row[2] == $name) {
//echo $result = '
$result .= '
<a href="gamesReceipes.php?id=' . $row[0] . '">
<li class="unread clickable-row">
<div class="name">
' . $row[1] . '
</div>
<div class="message">
Voir la préparation
</div>
</li>;';
}
}
echo $result;
?>
You could also simplify this.
As you are passing the name of the game to this script you could add that to the query as a search criteria like so and then remove a lot of unnecessary processing.
<?php
require_once("connect_database.php");
mysqli_set_charset($con, "utf8");
// init the $result var
$result = '';
if ( isset($_GET['name'] ) {
$name = $_GET["name"];
$sql="SELECT * FROM `games` WHERE `name` = '$name'";
$reponse = mysqli_query($con, $sql);
// I assume there is only one ro w that contains this name
// so the loop is not required now
while ($row = mysqli_fetch_array($reponse, MYSQLI_NUM)) {
$result .= '
<a href="gamesReceipes.php?id=' . $row[0] . '">
<li class="unread clickable-row">
<div class="name">' . $row[1] . '</div>
<div class="message">Voir la préparation</div>
</li>;';
}
} else {
$result = 'No name parameter passed';
}
echo $result;
exit;
?>
This question already has answers here:
How can I call PHP functions by JavaScript?
(13 answers)
Closed 8 years ago.
<?php
session_start();
function printTable() {
$server = "XXXXXXXX";
$user = "XXXXXXXXX";
$password = "XXXXXXXX";
$database = "XXXXXXXX";
$conn = mysql_connect($server, $user, $password);
mysql_selectdb($database, $conn);
$query = "SELECT Image, ISBN, Name, Vol, Release_date, publisher, price FROM products p";
$resultset = mysql_query($query, $conn); // retrieve data from database
if ($resultset == null || $resultset == 1) {
echo mysql_error(); // print SQL error
die(); // exit PHP program
}
$numFields = mysql_num_fields($resultset);
echo "<table border=2 align=center><tr>";
echo "</tr>";
for ($i=0; $i<(mysql_num_rows($resultset)); $i++) { // print records
$fields = mysql_fetch_row($resultset);
echo "<tr>";
echo "<tr class=$color><td><img width=100px src=$fields[0]></td>";
echo "<td> Name: " . $fields[2] . " (vol.". $fields[3] . ")</br>";
echo "<br> ISBN: " . $fields[1] . "</br>";
echo "<br> Publisher: " . $fields[5] . "</br>";
echo "<br> Release Date: " . $fields[4] . "</br>";
echo "<br> Price: HK$ " . $fields[6] . "</td>";
echo "<td><input type=\"submit\" value=\"Add to Cart\" onclick=\"combine($fields[1], '$fields[2]', $fields[3]);\"/></td>";
$fields = mysql_fetch_row($resultset);
if ($fields == null) break;
echo "<td><img width=100px src=$fields[0]></td>";
echo "<td> Name: " . $fields[2] . " (vol.". $fields[3] . ")</br>";
echo "<br> ISBN: " . $fields[1] . "</br>";
echo "<br> Publisher: " . $fields[5] . "</br>";
echo "<br> Release Date: " . $fields[4] . "</br>";
echo "<br> Price: HK$ " . $fields[6] . "</td>";
echo "<td><input type=\"submit\" value=\"Add to Cart\" onclick=\"combine($fields[1], '$fields[2]', $fields[3]);\"/></td>";
echo "</tr>";
}
echo "</table>";
}
mysql_close();
?>
<html>
<head>
<script>
function combine(value1, value2, value3) {
alert (value1 + value2 + value3);
//setcookie(value1);
}
</script>
</head>
<title>
Product Page
</title>
<body>
<body style="background:#A2A2AE">
<h1> <center> Product Page </center> </h1>
<p><center>-----------------------------------------------------------------------------------------------------------------------------------------------------------</center></p>
<?php printTable(); ?>
</body></html>
how I can run the function addcookies() to save value 1 as the cookies... Thank you!
function addcookies(value) {
$pid = $_POST['pid'];
$expiry = time() + 60 * 60 * 24 * 30;
// Update the number of items
if(isset($_COOKIE['count']))
$count = $_COOKIE['count'];
else
$count = 0;
// Put the item into shopping cart
$key = "item: ".$count;
setcookie($key, $pid, $expiry);
setcookie("count", $count+1, $expiry);
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
First of all, your html code isn't correct. You oppened body tag 2 times and your title tag is out of the head tag, it's not even in the body.
As Biffen said in the comment, you cannot run the php after the page has loaded. Instead, you can use ajax. Ajax Documentation
You have to create a file with your php code inside it, and then execute it with ajax without reloading the page. And as I see you have written in a comment: "Put the item into shopping cart". Do not store shopping cart items in, neither, browser cookies nor session. Use your database instead because data stored in either cookies or session will be vulnerable.
I need to preface my question with some history so you know what and who you are dealing with. I am a 75 year old just retired house painter who is building just this one website so that I can sell some of the stuff that I have done for many years as a hobby. I have a decent understanding of HTML and CSS and a lesser knowledge of PHP from browsing the internet. JavaScript knowledge is zilch.
This is an include file for the content in one of the sections of my website. It works fine with just one Mysqli query and no JavaScript, but with a lot of products to list I would like to swap the content so I wouldn't have to add more pages. The JavaScript is borrowed from a tutorial by Adam Khoury and I just plugged in my information to it.
My question is, can I use the LIMIT clause as a mechanism to swap the content of the page as I tried within the code below? At this point I am getting this error.
Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result,
boolean given in C:\wamp\www\elkcreek\includes\cabscontent1.php on line 37.
This line is:
while ($row = mysqli_fetch_assoc($result))
Thanks in advance for any help or just for reading this diatribe.
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
?>
<?php
require "scripts/connect_to_copy.php";
$contentVar = '';
$products = '';
$sql = '';
if (isset($_POST['contentVar'])) {$contentVar = $_POST['contentVar'];}
if ($contentVar == "con1")
{
$sql = mysqli_query($link, "SELECT * FROM cabs ORDER BY id LIMIT 0, 4" );
}
else if ($contentVar == "con2")
{
$sql = mysqli_query($link, "SELECT * FROM cabs ORDER BY id LIMIT 4, 8");
}
else if ($contentVar == "con3")
{
$sql = mysqli_query($link, "SELECT * FROM cabs ORDER BY id LIMIT 8, 12");
}
$result = mysql_query($sql)
while ($row = mysqli_fetch_assoc($result))
{
$pages = $row["pages"];
$left_image = $row["left_image"];
$product_name = $row["product_name"];
$price = $row["price"];
$ordering_number = $row["ordering_number"];
$sold = $row["sold"];
$products .=
'<div class="product">
<div class="product_pictures"><a href="' . $pages . '">
<img src="' . $left_image . '" alt="cabochon" width="150" height="200"/></a>
</div>
<div class="product_name"><h3>' . $product_name . '</h3></div>
<div class="price">$' . $price . '</div>
<div class="order_number">Order# C' . $ordering_number . '</div>
<div class="sold">' . $sold . '</div>
</div>';
}
?>
<script type="text/javascript" src="jquery-1.10.2.js"></script>
<script>
function swapContent(cv) {
$(".product").html('<img src="loader.gif"/>').show();
var url = "cabscontent1.php?";
$.post(url, {contentVar: cv} ,function(data) {
$(".product").html(data).show();
});
}
</script>
<div class="desc">CLICK ON PICTURES FOR LARGER PICTURES - DESCRIPTIONS
</div>
<div class="more_cabs">MORE CABS
1
2
3
</div>
<div class="product_column"><?php echo $products; ?></div>