$query = "SELECT * FROM abc";
if ($result = $db->query($query)) {
$row = $result->fetch_assoc();
while ($row = $result->fetch_assoc()) {
$data[] = array("a"=>$row["a"],
"b"=>$row["b"],
"c"=>$row["c"],
"d"=>$row["d"]
);
}
$result->close();
}
$db->close();
<?php foreach ($data as $row) { ?>
<form action="">
<div class="col-lg-3">
<input type="text" value="<?php echo $row['a'] ?>"/>
</div>
<div class="col-lg-3">
<input type="text" value="<?php echo $row['b'] ?>"/>
</div>
<div class="col-lg-3">
<input type="text" value="<?php echo $row['c'] ?>"/>
</div>
<div class="col-lg-3">
<input type="text" value="<?php echo $row['d'] ?>"/>
</div>
</form>
<?php } ?>
Above is the exact code that I used to retrieve all the row in a table. The strange part is that I have 5 row and it only show 4. The first row is missing. I wonder why.
In your code, you're calling $row = $result->fetch_assoc(); just before starting your while loop. This line is "consuming" your first raw and when you're entering in the loop, you move the cursor to the second row by calling this same method a second time.
The condition of the while loop is executed BEFORE the content, here you'll find more info about PHP While loop
To fix your code, remove this first line.
Related
I'm trying to echo a piece of text with PHP nested in it, anyone know how? I've tried it like this:
function update_category(){
global $connection;
if (isset($_GET['edit'])) {
$edit_cat_key = $_GET['edit'];
$query = "SELECT * FROM categories WHERE cat_id = {$edit_cat_key }";
$edit_cat_query = mysqli_query($connection, $query);
echo '<form action="categories.php" method="post">
<div class="form-group">
<label for="new-cat-title">New name of category</label>
<input value="<?php if(isset($cat_title)){echo $cat_title;} ?>" type="text" class="form-control" name="new-cat-title">
</div>
<div class="form-group">
<input class="btn btn-primary" type="submit" name="submit" value="Rename Category">
</div>
</form>';
while($row = mysqli_fetch_assoc($edit_cat_query)) {
$cat_title = $row['cat_title'];
$cat_id = $row['cat_id'];
}
}
}
It prints: <?php if(isset($cat_title)){echo $cat_title;} ?>
I've tried it like this:
<input value="' . <?php if(isset($cat_title)){echo $cat_title;} ?> . '" type="text" class="form-control" name="new-cat-title">
I'd do it like this (showing only the echo part inside the php code):
echo '<form action="categories.php" method="post">
<div class="form-group">
<label for="new-cat-title">New name of category</label><input value="';
if(isset($cat_title)){echo $cat_title;};
echo '" type="text" class="form-control" name="new-cat-title"></div>
<div class="form-group">
<input class="btn btn-primary" type="submit" name="submit" value="Rename Category">
</div>
</form>';
This echoes the two strings (in single quotes) and in between them the variable depending on the condition, keeping the double-quote pairs of the attribute values intact.
Echo is a php statement. You use it to display an output, as a string. What you need is, replacing echo ' with ?> and </form>'; with </form><?php. These closing(?>) and opening(<?php) tags let you decide which part of your document should be processed as PHP. So PHP will ignore the rest of the document.
Based on Johannes' answer I managed to figure out an answer. I need to close the PHP tags and instead of echoing the wished result, put it in the while loop.
Like this:
function update_category(){
global $connection;
if (isset($_GET['edit'])) {
$edit_cat_key = $_GET['edit'];
$query = "SELECT * FROM categories WHERE cat_id = {$edit_cat_key }";
$edit_cat_query = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($edit_cat_query)) {
$cat_title = $row['cat_title'];
$cat_id = $row['cat_id'];
?>
<input value="<?php echo $cat_title; ?>" type="text" class="form-control" name="cat_title">
<?php
}
}
}
Two tables Order and Line_items are Relate with each other as order_id is placed in line items,
now first populate the order table and then lineitems table on the base of order table's id.
All of the heppening in one isset() has two functions one add values in orders table and second function take order id and then populate the lineitems function.
Problems is for the very first lineitems the order id is "" in Html form's value attribute of order_id. (very hard for me to explain this problem).
Here is my Php isset() function.
if(isset($_POST['check_out'])){
$user_id = $_POST['user_id'];
$shipping_address = $_POST['shipping_address'];
$billing_address = $_POST['billing_address'];
$shipping_method_id = $_POST['shipping_method_id'];
$grand_total = $_POST['grand_total'];
$order->addOrder($user_id,$shipping_address,$billing_address,$shipping_method_id,$grand_total);
$order_id = $_POST['latestorder'];
$product_id = $_POST['product_id'];
$product_price = $_POST['product_price'];
$product_quantity = $_POST['product_quantity'];
$product_total = $_POST['product_total'];
if (empty($order_id)) {
$order_id=$order->latestOrderRecord();
$order_id=+1;
}
$id= count($product_id);
for ($i=0; $i <$id ; $i++) {
$line_items->insertInLineItems($order_id,$product_id[$i],$product_price[$i],$product_quantity[$i],$product_total[$i]);
// $shoping_cart->
header('location:../cart.php');
}
}
html form
<form method="post" action="n/GetPostData.php" class="woocommerce-shipping-calculator">
<td data-title="Shipping">
Flat Rate:
<span class="amount">$300.00</span>
<p><a data-toggle="collapse" aria-controls="calculator" href="#calculator" aria-expanded="false" class="shipping-calculator-button">Calculate Shipping</a></p>
<div id="calculator" class="shipping-calculator-form collapse">
<p id="calc_shipping_country_field" class="form-row form-row-wide">
<select rel="calc_shipping_state" class="country_to_state" id="calc_shipping_country" name="shipping_method_id">
<option>Select Shipment Method</option>
<?php $shipping_method=$shipment_method->allShipmentMethod();
while ($row=mysqli_fetch_assoc($shipping_method)) { ?>
<option value="<?php echo $row['id'] ?>"><?php echo $row['name']; ?></option>
<?php } ?>
</select>
</p>
<p id="calc_shipping_country_field" class="form-row form-row-wide">
<input type="text" id="calc_shipping_postcode" name="shipping_address" placeholder="Shipping Address" class="input-text">
</p>
<p id="calc_shipping_state_field" class="form-row form-row-wide validate-required">
<input type="text" id="calc_shipping_postcode" name="billing_address" placeholder="Billing Address" class="input-text">
</p>
</div>
</td>
</tr>
<tr class="order-total">
<th>Total</th>
<td data-title="Total">
<strong><span class="amount">$<?php echo $total; ?></span></strong>
<input type="hidden" name="grand_total" value="<?php echo $total ?>">
<input type="hidden" name="user_id" value="<?php echo $id ?>">
<?php $latestrecord=$order->latestOrderRecord(); ?>
<input type="hidden" name="latestorder" value="<?php echo $latestrecord ?>">
<?php $total=0; $all_cart_products=$shoping_cart->allShopingcartValue($id);
while ($row=mysqli_fetch_assoc($all_cart_products)) { ?>
<input type="hidden" name="product_id[]" value="<?php echo $row['product_id']; ?>">
<input type="hidden" name="product_quantity[]" value="<?php echo $row['quantity']; ?>">
<input type="hidden" name="product_price[]" value="<?php echo $row['price']; ?>">
<input type="hidden" name="product_total[]" value="<?php echo $row['total']; ?>">
<?php } ?>
<p><button type="submit" class="button" name="check_out" type="submit">Chcek Out</button></p>
</td>
</tr>
</form>
for the very first time when order table is empty the name="latestorder" show "" (no value).
Here is latestOrderRecord() function definition
public function latestOrderRecord()
{
$query="SELECT MAX(id) AS LatestRecord FROM orders";
$conn=$this->Connection();
$result = mysqli_query($conn,$query);
$num_rows = mysqli_num_rows($result);
if ($num_rows>0) {
while ($row=mysqli_fetch_assoc($result)) {
$latestrecord=$row['LatestRecord'];
}
}
return $latestrecord;
}
Issue is that, you are using header() redirection inside your for() loop:
for ($i=0; $i <$id ; $i++) {
header('location:../cart.php'); // that is the issue
}
You must need to use a variable for success in for loop, then you can use it outside the loop for redirection, something like:
HINT:
if($success){
header('location:../cart.php');
exit(); // always use exit() after header() otherwise script execution will not stop
}
Edit:
As per your comment, you are getting order id 0 in lineitem table, because you are inserting $_POST['latestorder'] value which is 0 because you dont have latest ID.
you need to insert the last inserted id of this query:
$order->addOrder($user_id,$shipping_address,$billing_address,$shipping_method_id,$grand_total);
return last inserted id from addOrder() method, and store it into a new variable and use this variable in your lineitem table something like:
$lastInsertID = $order->addOrder($user_id,$shipping_address,$billing_address,$shipping_method_id,$grand_total);
and, here $line_items->insertInLineItems($order_id,$product_id[$i],$product_price[$i],$product_quantity[$i],$product_total[$i]); replace $order_id with $lastInsertID
Make sure, method addOrder() returns last inserted ID.
Here in this code I am accepting data as an array and inserting it in the database. As I am using while loop I am having multiple input fields with same name as you can see in the HTML code below. What I want to do is, I want to add a check that if two fields are same then echo error saying two fields cannot be the same else insert the data. I could do it if there were two different input fields for the data like if($field1 == $field2){ echo "Error!"; else insert data. But here the field is only one with is giving multiple fields in a while loop. How can I add this check?
HTML form code:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<?php while($pro = $priq->fetch()){ extract($pro); ?>
<div class="row tbpad">
<div class="col-sm-3 col-xs-6">
<p><i class="fa fa-caret-right"></i> <?php echo $bk_title; ?></p>
</div>
<div class="col-sm-1 col-xs-1">
<div class="form-group">
<input type="text" class="form-control" name="priority[]" value="<?php echo $pr_priority; ?>">
<input type="hidden" class="form-control" value="<?php echo $bk_id; ?>" name="bkid[]">
</div>
</div>
</div>
<?php } ?>
<input type="submit" class="btn btn-orange" value="Set Priority" name="priority">
</form>
PHP code:
if(isset($_POST['priority'])){
$priority = (!empty($_POST['priority']))?$_POST['priority']:null;
$bkid = (!empty($_POST['bkid']))?$_POST['bkid']:null;
$iNumSets = count($priority);
for($i = 0; $i < $iNumSets; $i++){
$str = "INSERT INTO priorities(pr_book, pr_by, pr_priority)
VALUES('$bkid[$i]', '$sess', '$priority[$i]')";
$res = $PDO->prepare($str);
$res->execute();
if($res){
echo '<script>alert("Priority added successfully!");window.location = "view-order.php";</script>';
}else{
echo '<script>alert("Server Error! Please try back later.");window.location = "add-order.php";</script>';
}
}
}
Since $priority is an array which you get from $_POST['priority'], you could do the following:
$num_original = count($priority);
$num_unique = count(array_unique($priority));
if ($num_original != $num_unique) {
echo "One or more item were idendical!";
}
Also make sure you use mysql_real_escape_string() or similar methods on your $_POST input before you pass it into the SQL query. Otherwise your code is vulnerable to SQL injections!
while($row = mysql_fetch_array($result))
{
$a=$row['diagnosis'];
$b=$row['icd_code'];
echo' <div class="form-group"><div class="col-lg-8">
<input class="form-control" type="text" name="disease" value="'.$a.'">';
echo '</div>
<div class="col-md-11 pull-right mrgT10">
<input type="text" class="tags" name="icd" value="';echo $b.'" />
</div>
</div>'; } ?>
This is my php coding.When i process the form using anotherpage php with the following code
<?php
include('connect.php');
if(isset($_POST['submit']))
{
echo $disease=$_POST['disease'].'<br/>';
echo $icd=$_POST['icd'];
}?>
It will get only the last value like this.
MONOPLEGIA
447637006
Is there anyway to get all the values.Any suggestion or tips would be appreciated.
You can make it your textfields name as name="disease[]" , name="icd[]" instead of name="disease" and name="icd[]"
and you can retrive like
$diseases=$_POST['disease'];
foreach($diseases as $key=>$disease){
echo $disease;
echo $icd=$_POST['icd'][$key];
}
Also, change this value="';echo $b.'" into value="'.$b.'"
try this :
while($row = mysql_fetch_array($result))
{
$a=$row['diagnosis'];
$b=$row['icd_code'];
echo' <div class="form-group"><div class="col-lg-8">
<input class="form-control" type="text" name="disease[]" value="'.$a.'">';
echo '</div>
<div class="col-md-11 pull-right mrgT10">
<input type="text" class="tags" name="icd[]" value="';echo $b.'" />
</div>
</div>'; } ?>
and call the value at other php :
<?php
include('connect.php');
if(isset($_POST['submit']))
{
foreach($_POST['disease'] as $a=>$key){
echo $disease=$a[$key].'<br/>';
echo $icd=$_POST['icd'][$key];
}
}?>
hope this can help you.
You need to pass array so that you will get all values of result and serialize it and submit it to another form.
on next page you need to unserialize the array and you will get the whole array.
please try this code
<?php
while ($row = mysql_fetch_row($result)){
$a[] = $row[3];
$b[] = $row[4];
}
$var1 = serialize($a);
$var2 = serialize($b);
?>
**another_page.php**
<?php
print_r($_REQUEST);
$var1 = unserialize($_POST['b']);
print_r($var1);
die();
Hope U will get some thing...
Here is my situation:
I am building a multi language page where my language come out of MYSQL through a PDO statement. The language is selected through an ID inside my link.
For Example:
<div class="country"><a class="darkbrowntext" href="log?id=11111">
<div class="language"><p>Nederlands</p></div>
<div class="countryflag"><img src="images/Dutch.gif" width="220" height="145" alt="dutch"></div>
</a></div>
<div class="country"><a class="darkbrowntext" href="log?id=11112">
<div class="language"><p>English</p></div>
<div class="countryflag"><img src="images/english.gif" width="220" height="145" alt="french"></div>
</a></div>
On my log page i have the following code:
$languageid = (int) $_GET['id'];
if(isset($languageid)){
$_SESSION['languageid'] = $languageid;
}
else {
header('Location: error');
}
require('incl/connect.inc.php');
if(isset($languageid) && ($languageid == 11111)){
$column = 'language_nl';
}
elseif(isset($languageid) && ($languageid == 11112)){
$column = 'language_en';
}
$languagestmt = $db->prepare ("SELECT $column FROM attrib_language");
$languagestmt->execute();
$lrow = $languagestmt->fetch(PDO::FETCH_ASSOC);
If a have this table in my MYSQL:
ID language_nl language_en
1 Aanmelden Sign in
2 Afmelden Sign out
3 Naam Name
4 Voornaam First name
How will I be able to select the right thing in my array of my column to put it into the right labels see below. Do I have to work with foreach or do I have to change my fetch?
<div class="logtxt"><h3><?php echo $lrow['***********']; ?></h3></div>
<div class="logtxt"><h3><?php echo $lrow['***********']; ?></h3></div>
<label for="name" class="labelname"><?php echo $lrow['***********']; ?></label><input type="text" name="name" id="name" class="inputname" onclick="fncCheck();"/>
<label for="firstname" class="labelfirstname"><?php echo $lrow['***********']; ?></label><input type="text" name="firstname" id="firstname" class="inputfirstname" onclick="fncCheck();"/>
$languagestmt = $db->prepare ("SELECT ID,$column FROM attrib_language");
$lrow = $languagestmt->fetchAll(PDO::FETCH_COLUMN || PDO::FETCH_GROUP, 0);
<?php echo $lrow[1]; ?>
or
$languagestmt = $db->prepare ("SELECT language_en,$column FROM attrib_language");
$lrow = $languagestmt->fetchAll(PDO::FETCH_COLUMN || PDO::FETCH_GROUP, 0);
<?php echo $lrow['Sign In']; ?>
Whichever you prefer.
$res = $db->prepare ("SELECT a,b,c FROM my_table");
$res->execute();
while($row = $res->fetch(PDO::FETCH_ASSOC){
echo $row['a'] . $row['b'],$row['c'];
}
Notice the $row is an associative array where the members are the column names.
I suggest you print_r($lrow); or var_dump($lrow); to see your results in what shape or form. Also to have a cleaner view, echo "<pre>"; before it.
PDO::FETCH_ASSOC: returns an array indexed by column name as returned in your result set
So it should be:
<div class="logtxt"><h3><?php echo $lrow[$column][1]; ?></h3></div>
<div class="logtxt"><h3><?php echo $lrow[$column][2]; ?></h3></div>
<label for="name" class="labelname"><?php echo $lrow[$column][3]; ?></label><input type="text" name="name" id="name" class="inputname" onclick="fncCheck();"/>
<label for="firstname" class="labelfirstname"><?php echo $lrow[$column][4]; ?></label><input type="text" name="firstname" id="firstname" class="inputfirstname" onclick="fncCheck();"/>
However, if I were you I would store each of the translations in a different file (utf-8 encoded) instead of a database.