Having problems retrieving from mysql to populate form - php

I'm having a problem getting a result from my mysql database and getting it to popular a form. Basically, i'm making an item database where players can submit item details from a game and view the database to get information for each item. I have everything working as far as adding the items to the database and viewing the database. Now i'm trying to code an edit item page. I've basically reused my form from the additem page so it is showing the same form. At the top of my edititem page, I have the php code to pull the item number from the url as the item numbers are unique. So i'm using a prepared statement to pull the item number, then trying to retrieve the rest of the information from the database, then setting each information to a variable. Something is going on with my code but I can't find any errors. I entered a few header calls to debug by putting information in the url bar...But the headers aren't even being called in certain spots and im not getting any errors.
In the form, I used things like
<input name="itemname" type="text" value="<?php $edit_itemname?>">
and nothing is showing in the textbox. I'm fairly new to php and it seems much more difficult to debug than the other languages i've worked with..Any help or suggestions as far as debugging would be greatly appreciated. I posted my php code below as well if you guys see anything wrong...I shouldn't be having issues this simple! I'm pulling my hair out lol.
Thanks guys!
<?php
require 'dbh.php';
if (!isset($_GET['itemnumber'])) {
header("Location: itemdb.php");
exit();
}else{
$sql = "SELECT * FROM itemdb WHERE id = ?";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: edititem.php?error=sqlerror");
exit();
}else{
$getid = $_GET['itemnumber'];
mysqli_stmt_bind_param($stmt, "i", $getid);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
//Make sure an item is selected
if ($result == 0) {
$message = "You must select an item to edit!";
header("Location: edititem.php?Noresults");
exit();
}else{
while ($row = mysqli_fetch_assoc($stmt)) {
$edit_itemname = $row['name'];
$edit_itemkeywords = $row['type'];
$edit_itemego = $row['ego'];
$edit_itemweight = $row['weight'];
$edit_itemacordmg = $row['acordmg'];
$edit_itemtags = $row['tags'];
$edit_itemworn = $row['worn'];
$edit_itemaffects = $row['affects'];
$edit_itemloads = $row['loads'];
$edit_itemarea = $row['area'];
$edit_itemcomments = $row['comments'];
header("Location: edititem.php?testing");
}
}
}
}
?>

To get the value of $edit_itemname into the output you should be using <?= not <?php. Saying <?php will run the code, so basically that is just a line with the variable in it. You are not telling it to print the value in the variable.
If your whole line looks like:
<input name="itemname" type="text" value="<?= $edit_itemname?>">
That should give you what you are looking for. The <?= is the equivalent of saying echo $edit_itemname;
If you don't like using <?= you could alternatively say
<input name="itemname" type="text" value="<?php echo $edit_itemname; ?>">

Your code should be change to a more readable form and you should add an output - I wouldn't recomment to use <?= - and you need to choose what you're going to do with your rows - maybe <input>, <table> - or something else?
<?php
require 'dbh.php';
if (!isset($_GET['itemnumber'])) {
header("Location: itemdb.php");
exit();
} // no else needed -> exit()
$sql = "SELECT * FROM itemdb WHERE id = ?";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: edititem.php?error=sqlerror");
exit();
} // no else needed -> exit()
$getid = $_GET['itemnumber'];
mysqli_stmt_bind_param($stmt, "i", $getid);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
//Make sure an item is selected
if ($result == 0) {
$message = "You must select an item to edit!";
header("Location: edititem.php?Noresults");
exit();
} // no else needed -> exit()
while ($row = mysqli_fetch_assoc($stmt)) {
$edit_itemname = $row['name'];
$edit_itemkeywords = $row['type'];
$edit_itemego = $row['ego'];
$edit_itemweight = $row['weight'];
$edit_itemacordmg = $row['acordmg'];
$edit_itemtags = $row['tags'];
$edit_itemworn = $row['worn'];
$edit_itemaffects = $row['affects'];
$edit_itemloads = $row['loads'];
$edit_itemarea = $row['area'];
$edit_itemcomments = $row['comments'];
// does not make sense here: header("Location: edititem.php?testing");
// show your data (need to edited):
echo "Name: " + $edit_itemname + "<br/>";
echo "Area: " + $edit_itemarea + "<br/>";
echo "Comment: " + $edit_itemcomments + "<br/>";
// end of current row
echo "<hr><br/>"
}
?>

Related

PHP Form $_POST foreach stops after first iteration

I have the below PHP code which picks up the posted form data from another file, executes SELECT queries to find all related data form the various tables (SalesDB, CustDB and ProdDB), and then executes an INSERT INTO query to add a row into the 'SalesDB' table. The form has dynamically added rows, which gives each newly added row a unique ID, for example:
...<input type="text" id="prodName_1" name="prodName[]" value="">
...<input type="text" id="prodName_2" name="prodName[]" value="">
.
.
...<input type="text" id="prodName_Z" name="prodName[]" value="">
However, when the PHP script runs for e.g. 3 rows of product lines, it only executes the $queryinsert query for the first iteration and inserts the first product line of the form. Why won't it loop through the array? See the php script below:
<?php
$db = new SQLite3('../xxx.db');
if(!$db){
echo $db->lastErrorMsg();
exit;
}
if (empty($_POST['custID'])) {
$errorMSG = array("No customer selected");
echo json_encode($errorMSG, JSON_PRETTY_PRINT);
exit;
} else {
$custID = $_POST['custID'];
$queryInsert = $db->prepare("INSERT INTO 'SalesDB'
(SalesID,CustID,ProdID,ProdQty,ProdPrice,ProdCurr,ProdVAT,SalesPrice,SalesVAT,SalesSum)
VALUES (?,?,?,?,?,?,?,?,?,?)");
$queryInsert->bindParam(1,$salesID);
$queryInsert->bindParam(2,$custID);
$queryInsert->bindParam(3,$prodID);
$queryInsert->bindParam(4,$prodQty);
$queryInsert->bindParam(5,$prodPrice);
$queryInsert->bindParam(6,$prodCurr);
$queryInsert->bindParam(7,$prodVAT);
$queryInsert->bindParam(8,$salesPrice);
$queryInsert->bindParam(9,$salesVAT);
$queryInsert->bindParam(10,$salesSum);
$querySalesID = "SELECT MAX(SalesID) AS max_SalesID FROM 'SalesDB'";
$resultSalesID = $db->query($querySalesID);
while ($row = $resultSalesID->fetchArray()) {
$salesID = $row['max_SalesID'] + 1;
}
foreach($_POST['prodName'] as $prodName => $value) {
if (!$value) {
$errorMSG = array("Empty product fields");
echo json_encode($errorMSG, JSON_PRETTY_PRINT);
exit;
} elseif ($value == "Product not found") {
$errorMSG = array("Invalid products in order form");
echo json_encode($errorMSG, JSON_PRETTY_PRINT);
exit;
}
$queryProd = "SELECT * FROM `ProdDB` WHERE ProdName LIKE '%$value%'";
$resultProd = $db->query($queryProd);
while ($row = $resultProd->fetchArray()) {
$prodID = $row['ProdID'];
$prodPrice = $row['ProdPrice'];
$prodQty = $row['ProdQty'];
$prodVAT = $row['ProdVAT'];
$prodCurr = $row['ProdCurr'];
$salesPrice = $prodQty * $prodPrice;
$salesVAT = number_format($prodQty * $prodPrice * $prodVAT,2);
$salesSum = $salesPrice + $salesVAT;
}
$result = $queryInsert->execute();
}
}
?>
Please also note that I am aware that I am (most likely) making a lot of mistakes when it comes to security practices or programming standards, but this whole thing (PHPDesktop > https://github.com/cztomczak/phpdesktop) will get packed into an EXE file which will run locally only (no need for an online connection as the SQLite3 DB gets packed in with the EXE), and I am still figuring out how to program this in the first place, so efficient and tidy coding are not high on my list yet ;-)
There are some issues in the script:
1) Instead of doing exit inside the foreach, do continue to skip the single actual iteration.
As in the official documentation:
continue is used within looping structures to skip the rest of the
current loop iteration and continue execution at the condition
evaluation and then the beginning of the next iteration.
Try this code:
foreach($_POST['prodName'] as $prodName => $value) {
if (!$value) {
$errorMSG = array("Empty product fields");
echo json_encode($errorMSG, JSON_PRETTY_PRINT);
continue;
} elseif ($value == "Product not found") {
$errorMSG = array("Invalid products in order form");
echo json_encode($errorMSG, JSON_PRETTY_PRINT);
continue;
}
$queryProd = "SELECT * FROM `ProdDB` WHERE ProdName LIKE '%$value%'";
$resultProd = $db->query($queryProd);
while ($row = $resultProd->fetchArray()) {
$prodID = $row['ProdID'];
$prodPrice = $row['ProdPrice'];
$prodQty = $row['ProdQty'];
$prodVAT = $row['ProdVAT'];
$prodCurr = $row['ProdCurr'];
$salesPrice = $prodQty * $prodPrice;
$salesVAT = number_format($prodQty * $prodPrice * $prodVAT,2);
$salesSum = $salesPrice + $salesVAT;
}
$result = $queryInsert->execute();
}
2) your query are using user inputs without check their contents, so your script maybe open to SQLInjection!
$queryProd = "SELECT * FROM `ProdDB` WHERE ProdName LIKE '%$value%'";
3) if the query does return nothing, the script does not enter in the while loop, so it seems that the foreach do only one iteration but instead it do all iterations without enter in the while because of empty result from that query.
I suggest to you to debug all pieces of your code by printing out variables content using var_dump, e.g.:
$a = array(1, 2, array("a", "b", "c"));
var_dump($a);

How to differentiate data to be read between two tables when username and password is passed?

I am using volley in my mobile development login and instead of one table, I used two.
At first I was having trouble because my login process only shows the data of the client. When I put on my username and password as client, it does show but when I use an username and password from the stylist, still a client's data shows. Now I discovered it's from my main menu's problem because I have a php code for reading details and what is there is only reading the client's table. What I am needing help for now is how to correctly read the data of the two tables and pass it for my main menu?
This is my readDetail.php
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$id = $_POST['id'];
require_once 'connect.php';
$sql = "SELECT * FROM client WHERE client_id=$id";
$response = mysqli_query($conn, $sql);
// HOW CAN I ALSO SELECT FROM STYLIST AND GO INSIDE THE QUERY
// FOR PASSING THE DATA? MY SQL QUERY IS ONLY FOR CLIENT AND THIS
// IS WHY I ONLY GET DATA FROM CLIENT. CAN SOMEONE POINT ME OUT
// WHAT TO QUERY TO ALSO PASS FOR THE STYLIST DATA?
$result = array();
$result['read'] = array();
if(mysqli_num_rows($response) === 1){
if($row = mysqli_fetch_assoc($response)){
$h['name'] = $row['name'];
$h['phone_number'] = $row['phone_number'];
$h['gender'] = $row['gender'];
$h['address'] = $row['address'];
$h['occupation'] = $row['occupation'];
$h['birth_date'] = $row['birth_date'];
$h['user_type'] = $row['user_type'];
$h['image'] = $row['photo'];
array_push($result["read"], $h);
$result["success"] = "1";
$result["message"] = "success";
echo json_encode($result);
}
}else{
$result["success"] = "0";
$result["message"] = "$sql";
echo json_encode($result);
}
}
?>
This has been solved by also adding a usertype to each of my tables. also passing to their parameters and bringing if statements into it so it defines what table to open :) hihi

PHP - Form error alerts displays on page load

i am a newbee and just learning along the way. I have two forms on a page (I have only shown one of them as the other form is the same code with different variables). Both their error messages display on page load. How can I stop this?
I have read multiple posts regarding this but I still cannot find a solution.
<?php
if(isset($_POST['Update'])) {
$c_fname = $_POST['fname'];
$c_lname = $_POST['lname'];
$c_email = $_POST['email'];
$c_phone = $_POST['phone'];
// Save $_POST to $_SESSION
//query
$insert_det = "INSERT INTO Cus_acc_details(CUS_Fname,CUS_Lname,Cus_Email,CUS_Phone)
VALUES (?,?,?,?)
ON DUPLICATE KEY
UPDATE
Cus_acc_details.CUS_Fname = '$c_fname',
Cus_acc_details.Cus_Lname = '$c_lname',
Cus_acc_details.Cus_Email = '$c_email',
Cus_acc_details.CUS_Phone = '$c_phone'";
$stmt = mysqli_prepare($dbc, $insert_det);
//new
// $stmt = mysqli_prepare($dbc, $insert_c);
//debugging
//$stmt = mysqli_prepare($dbc, $insert_c) or die(mysqli_error($dbc));
mysqli_stmt_bind_param($stmt, 'sssi', $c_fname, $c_lname, $c_email, $c_phone);
/* execute query */
$r = mysqli_stmt_execute($stmt);
// if inserted echo the following messges
if ($r) {
echo "<script> alert('Saved')</script>";
}
} else {
echo "<b>Oops! we have an issu </b>";
}
?>
You have an else after your if (isset($_POST['Update'])). Inside that else you are displaying errors as if the user tried to submit the form. $_POST['Update'] will only be set if the user tried to submit the form. Move that else inside your if:
if (isset($_POST['Update'])) {
/* a bunch of code to insert into the DB */
// if inserted echo the following messges
if ($r) {
echo "<script> alert('Saved')</script>";
}else{
echo "<b>Oops! we have an issu </b>";
}
}
In Addition:
The commenter is right. You are at risk for SQL Injection. Please use prepared statements instead.
The problem is your else statement is running every time the variable $_POST['Update'] is not set.
One way to fix this is to move your error message inside your form checking code. Something like this would work:
if (isset($_POST['Update'])) {
/* unchanged code snipped */
if ($r) {
echo "<script> alert('Saved')</script>";
} else {
echo "<b>Oops! we have an issu </b>";
}
}
Hope that helps!

Passing variables from page to page

I am trying to pass a variable from one page to another using $_GET, and I can't seem to get it to work. I would appreciate any help.
First I create a link based on the results from the database here.
clients.php
require_once("../auth/config.class.php");
require_once("../auth/auth.class.php");
$config = new Config;
$dbh = new PDO("mysql:host={$config->dbhost};dbname={$config->dbname}", $config->dbuser, $config->dbpass);
$auth = new Auth($dbh, $config);
$uid = $auth->SessionUID($_COOKIE['authID']);
$query = $dbh->prepare("SELECT fname, lname, id FROM client WHERE uid=? ORDER by id");
$query->execute(array($uid));
$rslt = $query->fetchAll(PDO::FETCH_ASSOC);
foreach($rslt as $row ){
echo "<a href=../pages/status.php?id=$row[id]>$row[fname]<br></a>";
}
The result from the link are listed on this page
status.php
$cid = $_GET['id'];
$query = $dbh->prepare("SELECT function FROM funcbathing WHERE cid=?");
$query->execute(array($cid));
$rslt = $query->fetch(PDO::FETCH_ASSOC);
if (empty($rslt)){
header('Location: ../views/careplan.php');
echo $cid
}
else{
header('Location: ../views/home.php');
}
I would like to pass the $cid to this page in a text box, but I can't seem to get it work. Here's the page that the id should get passed to.
careplan.php this is a bigger form but I removed the irrelevant information for simplicity.
<input type="text" name="clientid" value="<?php if(isset($_GET['cid'])) { echo $_GET['cid']; } ?>" />
header('Location: ../views/careplan.php?cid='.$cid);
EDIT:
You should learn to print the strings in a valid manor, check error_reporting(E_ALL); and display_errors=on with your string.
then try this:
echo ''.$row["fname"].'<br>';
or:
echo sprintf('%s<br>', $row['id'], $row['fname']);
or even:
echo "{$row["fname"]}<br>";
or any of the other hundreds way to write a valid string

Retrieve user input from database

I am trying to display the customer record from my database thats is determined by the id.
What I already have is a return where the id = 42. What I want to do is make it where the record returned is based on the id number that the user inputs on a previous page, which is $customerid. Any suggestions?
<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo $row[0]; // 42
echo $row[1]; // the email value
?>
You can get the parameter passed to the PHP via GET or POST using $_GET["param_name"] and $_POST["param_name"] respectively.
So if your page is called using
http://path/to/page.php?id=99
You can get 99 in $_GET["id"]
Similar for POST.
Not having seen your form, I am assuming that you will POST the data.
Here is my suggestion for how to handle the data:
$id=isset($_POST['id'])&&is_numeric($_POST['id'])?$_POST['id']:false;
if ($id) {
$result = mysql_query("SELECT id,email FROM people WHERE id = $id;");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo $row[0]; // 42
echo $row[1]; // the email value
} else {
echo "ERROR: No ID specified.";
}
Also, consider using PDO as mysql_* statements are depreciated. At the least, investigate how to prevent SQL Injection.
Try this:
search.php
<form action="show_record.php" method="post">
<input name="customer_id" />
</form>
show_record.php
<?php
// use $_REQUEST to get a parameter from POST OU GET request method
$id = isset($_REQUEST["customer_id"]) ? $_REQUEST["customer_id"] : 0;
$id = mysql_real_escape_string(); // prevent sql inject
$result = mysql_query("SELECT id,email FROM people WHERE id = '$id'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo $row[0]; // 42
echo $row[1]; // the email value
?>
So, you can request the page show_record.php from POST or GET, anyway the answer will be the same.
Via GET:
localhost/show_record.php?customer_id=42

Categories