PHP regex undifined offset when used in function - php

I have a string consists of multiple lines. I am getting this string from imap (as an email body). I get this string as follows:
$mail_body = imap_fetchbody($mbox,$msgno,1);
My regex is:
preg_match("/HEX}(.*).php/", $string, $matches);
If I describe this string manually like:
$_string = "It is too long therefore I do not paste it here"
And If I do that:
preg_match("/HEX}(.*).php/",$_string,$matches);
$new_string = $matches[1];
echo $new_string;
It works perfectly.
But when I passed string to a function in same class:
$this->some_funtion($mail_body);
It gives me an error although I am doing the same thing in function:
preg_match("/HEX}(.*).php/",$_string,$matches);
$new_string = $matches[1];
echo $new_string;
Error: Notice: Undefined offset: 1
Why should it happen? I am doing the very same thing!
Thanks for your help!
EDIT
private function get_directory_path($string = '')
{
preg_match("/HEX}(.*).php/", $string, $matches);
$new_string = $matches[1];
echo $new_string;
}
I pass parameter as follows:
$mail_body = imap_fetchbody($mbox,$msgno,1.2);
if(!strlen($mail_body)>0){
$mail_body = imap_fetchbody($mbox,$msgno,1);
}
$this->get_directory_path($mail_body);

There are several things that might make the pattern not match. Newlines, spaces and tabs being the biggest problem because when you echo out to the screen and copy/paste to test they don't copy. Perhaps echo out the $mail_body variable inside of <pre> tags before passing it to the function or echo and view the source.
The easy way to fix it is to add the s modifier so that the dot (.) character matches newlines. So /pat{2}ern/s. But that might not give you the result you want. Without a full output of the string and what you expect from it (or what you are using it for), it wouldn't be possible to tell.

<?php
include('dataconn.php');
$result=mysql_query("select * from product");
while($row=mysql_fetch_assoc($result))
{
echo "<p>$row[Product_Name]</p>";
echo "<p>$row[Product_Quantity]</p>";
echo "<p>Add To Cart</p>";
}
?>
logout
/*--add to cart page--*/
<?php
/* ----------- ADD TO CART PAGE ----------------*/
include("dataconn.php");
$product_id = isset($_GET['pid']) ? $_GET['pid'] : null;
$action = isset($_GET['action']) ? $_GET['action'] : null; //the action
$quantity=isset($_GET['qty']) ? $_GET['qty'] : null;
?>
<html>
<head>
<title>View Cart</title>
</head>
<body>
<?php
$customer_id=$_SESSION['customer_id'];
$result=mysql_query("select * from product");
$row=mysql_fetch_assoc($result);
switch($action)
{
//decide what to do
case "add":
$_SESSION['cart'][$product_id]++;
break;
case "remove":
$_SESSION['cart'][$product_id] = 0;
unset($_SESSION['cart'][$product_id]);
header("Location: payment.php");//if the quantity is zero, remove it completely (using the 'unset' function) - otherwise is will show zero, then -1, -2 etc when the user keeps removing items.
break;
case "empty":
unset($_SESSION['cart']); //unset the whole cart, i.e. empty the cart.
header("Location: payment.php");
break;
}
//------- for checkout ---------
if(isset($_SESSION['cart']) && $_SESSION['cart']) {
$total = 0;
echo "<form name='cart' method='POST' action=''>";
echo "<table border=\"1\" padding=\"3\" width=\"100%\" class=\"data-container\">";
echo "<td colspan=\"4\" align=\"right\"><img src=\"image/delete.png\"/></td>";
foreach($_SESSION['cart'] as $product_id => $quantity)
{
$sql = sprintf("SELECT * FROM product WHERE Product_ID = %d;", $product_id);
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0)
{
$itemsInfo = mysql_fetch_assoc($result);
$cost = $itemsInfo["Product_Price"] * $quantity;
$total = $total + $cost; //add to the total cost
echo "<tr>";
//show this information in table cells
echo "<td align=\"center\">".$itemsInfo["Product_Name"]."</td>";
//along with a 'remove' link next to the quantity - which links to this page, but with an action of remove, and the id of the current product
echo "<td align=\"center\">$quantity </td>";
echo "<td align=\"center\">RM $cost</td>";
echo "<td align=\"center\"><img src=\"image/remove.png\"/></td>";
echo "</tr>";
}
}
//show the total
echo "<tr>";
echo "<td colspan=\"2\" ></td>";
echo "<td align=\"center\">Total</td>";
echo "<td colspan=\"2\" align=\"center\">RM $total</td>";
echo "</tr>";
echo "</table>";
echo "</form>";
}
?>
<br>
<div>
<span style="margin-left: 88%"><input type="submit" name="shopping_more" class="custom-button" value="Back To Shopping"/></span>
</div>
</html>

Related

PHP Notice: Undefined offset: 36

I have a simple php checkout but when adding the product to basket i get the following error:
PHP Notice: Undefined offset: 36 in C:\inetpub\wwwroot\shopping\cart.php on line 76
If i then refresh the page or go back to add another product it displays a product fine, it seems to be when adding to first product to the cart we get this error. any help would be much appreciated as all the answers i have tried have not worked.
<?php
// connect to the database
include("databasedrop.php");
?>
<div class="post">
<h2>Shopping Basket<span class="title-bottom"> </span></h2>
</div>
<!-- End Post -->
<?php
if (empty($_GET['id'])) {
$_GET['id'] = "";
}
$ProductID = $_GET['id']; //the product id from the URL
$action = $_GET['action']; //the action from the URL
//if there is an product_id and that product_id doesn't exist display an error message
switch ($action) { //decide what to do
case "add":
$_SESSION['cart'][$ProductID] ++; //add one to the quantity of the product with id $product_id
break;
case "remove":
$_SESSION['cart'][$ProductID] --; //remove one from the quantity of the product with id $product_id
if ($_SESSION['cart'][$ProductID] == 0)
unset($_SESSION['cart'][$ProductID]); //if the quantity is zero, remove it completely (using the 'unset' function) - otherwise is will show zero, then -1, -2 etc when the user keeps removing items.
break;
case "empty":
unset($_SESSION['cart']); //unset the whole cart, i.e. empty the cart.
break;
}
?>
<?php
if (empty($_SESSION['cart'])) {
$_SESSION['cart'] = "";
}
if ($_SESSION['cart']) { //if the cart isn't empty
//show the cart
echo "<table border=\"1\" padding=\"3\" width=\"40%\">"; //format the cart using a HTML table
//iterate through the cart, the $product_id is the key and $quantity is the value
foreach ($_SESSION['cart'] as $ProductID => $quantity) {
//get the name, description and price from the database - this will depend on your database implementation.
//use sprintf to make sure that $product_id is inserted into the query as a number - to prevent SQL injection
if ($stmt = $conn->prepare("SELECT * FROM products WHERE ProductID=?")) {
$stmt->bind_param("i", $ProductID);
$stmt->execute();
$stmt->bind_result($ProductID, $Title, $Description, $Price, $Stock, $Image, $Category, $Status);
$stmt->fetch();
// show the form
}
$total = "";
$line_cost = $Price * $quantity; //work out the line cost
$total = $total + $line_cost; //add to the total cost
echo "<tr>";
//show this information in table cells
echo "<td align=\"center\">$Title</td>";
//along with a 'remove' link next to the quantity - which links to this page, but with an action of remove, and the id of the current product
echo "<td align=\"center\">$quantity X</td>";
echo "<td align=\"center\">$line_cost</td>";
echo "</tr>";
}
//show the total
echo "<tr>";
echo "<td colspan=\"2\" align=\"right\">Total</td>";
echo "<td align=\"right\">$total</td>";
echo "</tr>";
//show the empty cart link - which links to this page, but with an action of empty. A simple bit of javascript in the onlick event of the link asks the user for confirmation
echo "<tr>";
echo "<td colspan=\"3\" align=\"right\">Empty Cart</td>";
echo "</tr>";
echo "</table>";
} else {
//otherwise tell the user they have no items in their cart
echo "You have no items in your shopping cart.";
}
?>
Shot in the dark, but only solution I can see.
Do you ever create the $_SESSION['cart']-array?
Try this:
switch ($action) {
case "add":
if (!isset($_SESSION['cart'][$ProductID])) {
$_SESSION['cart'][$ProductID] = 1;
}
else {
$_SESSION['cart'][$ProductID]++;
}
break;

How to display information in another PHP Page

I am having trouble with a mini shopping cart. I have created the mini shopping cart and when a product is added it goes into the Basket page. However, i want to create a checkout page. How do i grab the products in the basket and put it in a checkout page.
So For example, the check out page will look like this
ITEM NAME, ITEM MODEL, ITEM PRICE
TOTAL OF ITEMS
CHECKOUT BUTTON (links to a payment system)
This is my Basket.php code:
<?php
$bikecode = $_GET['id']; //the product id from the URL
$action = $_GET['action']; //the action from the URL
if($bikecode && !productExists($bikecode)) {
die("Product Doesn't Exist");
}
switch($action) { //decide what to do
case "add":
$_SESSION['cart'][$bikecode]++; //add one to the quantity of the product with id $bikecode
break;
case "remove":
$_SESSION['cart'][$bikecode]--; //remove one from the quantity of the product with id $bikecode
if($_SESSION['cart'][$bikecode] == 0) unset($_SESSION['cart'][$bikecode]); //if the quantity is zero, remove it completely (using the 'unset' function) - otherwise is will show zero, then -1, -2 etc when the user keeps removing items.
break;
case "empty":
unset($_SESSION['cart']); //unset the whole cart, i.e. empty the cart.
break;
}
if($_SESSION['cart']){
echo "<table width=\"100%\">";
foreach($_SESSION['cart'] as $bikecode => $quantity) {
$sql = sprintf("SELECT BikeCode, Model, Price FROM Bike WHERE BikeCode = '%s';", $bikecode);
$result = mysqli_query($con, $sql);
if(mysqli_num_rows($result) > 0) {
list($bikecode, $model, $price) = mysqli_fetch_row($result);
$cost = $quantity * $price;
$total = $total + $cost;
echo "<tr><th>BikeCode:</th><th>Model:</th><th>Quantity:</th><th>Price:</th></tr>";
echo "<tr>";
echo "<td align=\"center\">$bikecode</td>";
echo "<td align=\"center\">$model</td>";
echo "<td align=\"center\">$quantity X</td>";
echo "<td align=\"center\">£$cost</td>";
echo "</tr>";
}
}
echo "<tr>";
echo "<td colspan=\"3\" align=\"right\">Total</td>";
echo "<td align=\"right\">£$total</td>";
echo "</tr>";
echo "<tr>";
echo "<td colspan=\"4\" align=\"right\">Empty Cart</td>";
echo "</tr>";
echo "</table>";
}else{
echo "You have no items in your shopping cart.";
}
function productExists($bikecode) {
$sql = sprintf("SELECT * FROM Bike WHERE BikeCode = '%s';", $bikecode);
return mysqli_num_rows(mysqli_query($con, $sql)) > 0;
}
?>
As long as you have a session_start(); on top of every page you should be able to use the exact same foreach loop as you do in this piece of coding. The session with the information would just be carried over to the next page.
Assume you have a page called test.php with the following code:
<?php
session_start();
$_SESSION['test'] = 1;
echo $_SESSION['test'];
?>
Then to access the test variable in othertest.php page,simply do the following:
<?php
session_start();
echo $_SESSION['test']; ?>
You forgot to add session_start() to the top of your php file. I recommend adding session_start() to a separate file and then including that file in each of the php pages that uses session variables.

PHP SESSION HTML table carrying issue

I am adding items to my cart.php using an add in the URL.
case "add":
if (isset($_SESSION['cart'][$comic_id])) {
$_SESSION['cart'][$comic_id]++;
} else {
$_SESSION['cart'][$comic_id] = 1;}
... My items are presented into an HTML table in the cart.php. I just want to then re-call specific variables from the array in the checkout.php so the customer can confirm the order total along with their personal details.
I can only seem to carry the last added item/row over using SESSION variable when I use the following:
$_SESSION['totalnameqty']=$name . " " . $qty . " " . $cost;
...and then use an echo on the checkout.php page:
$totnamqty=$_SESSION['totnamqty'];
echo $totnamqty;
... I want to carry all items $name, $qty & $cost added to the HTML table in the cart.php to the checkout.php not just 1 item/row. Unsure of how to do this or if it is possible. Can somebody help?
Here is my cart.php:
if (isset($_SESSION['cart'][$comic_id])){
echo "<table border=\"0\" padding=\"10\" width=\"80%\">";
echo "<td colspan=\"1\" align=\"left\">Continue Shopping</div>";
echo "<td colspan=\"6\" align=\"right\">Empty Cart</td>";
echo "<tr height=\"20px\">";
echo "<tr height=\"20px\">";
echo "<td align=center>Image</td><td align=center>Title</td><td align=center>Description</td><td colspan=3 align=center>Copies (+/-)</td><td align=center>Price</td>";
echo "<tr height=\"20px\">";
foreach($_SESSION['cart'] as $comic_id => $qty) {
$sql = sprintf("SELECT title, description, cost, image_thumbnail
FROM comic
WHERE comic_id = %d;",$comic_id);
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0) {
list($name, $description, $price, $image_thumbnail) = mysql_fetch_row($result);
$cost = $price * $qty;
$total = $total + $cost;
$cost = number_format($cost,2);
$total = number_format($total,2);
$description = substr($description, 0, 250);
echo "<br><tr>";
echo "<td width=\"10px\" align=\"center\"><img height=100 align=center src=\"$image_thumbnail\">";
echo "<td align=\"center\">$name</td>";
echo "<td width=\"40%\" align=\"center\">$description...<a href=comic_dyn.php?comic_id=$comic_id>More Info</td>";
echo "<td width=\"30px\" align=\"center\">+<br><td align=\"center\">$qty <td width=\"20px\" align=\"center\">-</td>";
echo "<td align=\"right\">$$cost</td>";
echo "</tr>";
}
}
echo "<br><tr><tr height=100px>";
echo "<td><td><td colspan=\"4\" align=\"right\">Total:</td>";
echo "<td width=\"60px\" align=\"right\">$$total</td>";
echo "<tr><td colspan=\"7\" align=\"right\">Proceed to Checkout";
echo "<tr height=\"50px\">";
echo "</table>";
}else{
echo "Your cart is currently empty.";
echo "<br><br><td colspan=\"1\" align=\"left\">Continue Shopping</div>";
}
//session variables (to be carried to checkout.php
$_SESSION['cost']=$cost;
$_SESSION['name']=$name;
$_SESSION['qty']=$qty;
$_SESSION['totnamqty']=$name . " " . $qty . " " . $cost;
You're setting $name, $qty and $cost values inside a loop, therefore you are accessing the last set values below/outside of the loop. Also, you're using $comic_id at the beginning but below are using that same variable in your foreach statement. I'm guessing you can remove the foreach and instead use: $qty = $_SESSION['cart'][$comic_id]?
Otherwise, assuming the isset() at the top is incorrect, and that you are trying to loop each $comic_id from the cart; then you want to index your 'cost', 'name', 'qty' and 'tonamqty' values per $comic_id. eg. use something like this inside your foreach loop: $_SESSION['comics'][$comic_id]['cost'] = $cost;
However, I think a checkout approach without using session variables is more appropriate. I'd post what the user currently sees to checkout.php, rather than using the session data. Assume the session was accessed from multiple tabs and the user clicks checkout on an outdated tab. If using session variables, the server is only aware that the user requested to checkout the most recent items in the session, not what was actively visible.

Form submission adds a <br> in front of the beginning text in the form

Ok, I am using a PHP editing form (previous person built) that submits data into an MSSQL database this works fine however when the information is submitted into the database and later retrieved the the form page (for editing) there is a <br> at the beginning of the text. If the fields start with a <ul> that <br> is not inserted. I have been trying to figure out how to stop this. One thing I tried ends up removing all <br> in the text which makes the formatting disappear, How can I keep it from inserting the <br> at the top but keeping the <br> everywhere else? here is the code I have: ( I am giving you everything up to the first field where I have the issue appear)
function fromhtml ($x) {
$x = preg_replace("/<p>/i","\n\n",$x);
//$x = preg_replace("/<br>/i","\n",$x);
$x = preg_replace("/<li>/i","\n<li>",$x);
return $x;
}
$PHP_SELF = $_SERVER['PHP_SELF'];
$course_id = #$_GET["course"];
if ($course_id == "") {
$sqlquery = "SELECT id, title, goals, outline, reference, deliverymode, updated2 = CONVERT(VARCHAR(19), updated, 120)
FROM courses WHERE division_id = '$division_id' ORDER by id";
$result = mssql_query($sqlquery);
$number = mssql_num_rows($result);
print "<table border=1 id=\"content_table\"><tr><th>ID</th><th>Title</th><th>Status</th><th>Last modified</th></tr>\n";
$i = 0;
while ($number > $i) {
$course_id = mssql_result($result,$i,"id");
$reference = mssql_result($result,$i,"reference");
$updated = mssql_result($result,$i,"updated2");
print "<tr><td>";
if ($reference == "") {
print "<a href=$PHP_SELF?division=$division_id&course=$course_id>$course_id</a>";
} else {
print "$course_id";
}
print "</td><td>";
print mssql_result($result,$i,"title");
print "</td><td>";
if ($reference == "") {
if ( (mssql_result($result,$i,"goals")=="") and (mssql_result($result,$i,"outline")=="") ) {
print "<b>No syllabus, or incomplete</b></td>";
}
} else {
print "Based on $reference";
}
print "</td><td>$updated</td>\n";
print "</tr>\n";
$i++;
}
print "</table>";
exit;
}
$sqlquery = "SELECT * FROM courses WHERE id = '$course_id'";
$result = mssql_query($sqlquery);
$number = mssql_num_rows($result);
if ($number == 0) {
print "<html><body>";
print "No course with the ID \"$course_id\" exists in the course database.";
print "</body></html>";
exit;
}
$i = 0;
$description = fromhtml(mssql_result($result,$i,"description"));
print "<html><head><title>DACC Course Syllabus - $course_id</title>";
print "<script language=\"JavaScript\" type=\"text/javascript\" src=\"/rte/richtext2.js\"></script>";
?>
<script language="JavaScript" type="text/javascript">
<!--
initRTE("/rte/images/", "/rte/", "");
//-->
function submitForm() {
updateRTEs();
document.edit-course.submit();
return false;
}
</script>
<?php
print "</head><body>\n";
//Begin Form
print "<form name=\"edit-course\" id=\"edit-form\" method=\"post\" action=\"write.php?course=$course_id\" onSubmit=\"return submitForm()\">\n";
print "<fieldset>";
print "<label for=\"description\">Course Description</label>";
$description=addslashes(preg_replace('`[\r\n]`','',$description));
?>
<script language="JavaScript" type="text/javascript">
<!--
writeRichText('description', '<?php print $description; ?>', 200, 300, true, false);
//-->
</script>
<?php
print "</fieldset>";
It that BR is at very very beginning of string then use this
$x = preg_replace("/^<br(\/|)>/i","\n",$x);
instead of that commented line
preg_replace has a fourth parameter, $limit. Setting this to 1 would limit the preg_replace to the first occurence. Alternatively you could use the regular expression ^<br>. This would only replace <br> when it is at the beginning of the string.
Edit: Sorry, I misunderstood your problem. Use $variable=preg_replace("/^<br>/i", "", $variable); to strip the first <br>.

PHP - "if" in "while" problems to alternate html table rows colour

$banana=0;
$view = mysql_query('SELECT ......') or die ('Encountered an error.') ;
while($rows3=mysql_fetch_array($view))
{
$total_price2=$rows3['qty']*$rows3['number'];
$banana = $banana + 1;
if ($total_price2!=0)
{
if ($banana %2 ==0)
{
echo "<tr class=\"alt\">";
}
else
{
echo "<tr>";
}
echo "<td>".$rows3['member']."</td>";
echo "<td>".$rows3['payment']."</td>";
echo "<td>$".number_format($total_price2,2)."</td>";
}
echo "</tr>";
}
Problems:
The "banana" alternates the colour of the table row (class="alt") by using modulus (%) to check if banana is a odd number.
Not Working, I see the browser is self-closing the opening <tr> tag.
eg:
<tr><td>person</td><td>data</td><td>$10.00</td></tr>
<tr class="alt"></tr> (Repeats in this fashion)
UPDATE
I have discovered that the reiterating banana always returns ODD NUMBERS: 1 , 3, 5, etc
MySQL is not running correctly
SELECT table1.member, table1.paid, table1.payment,table2.qty,table3.number FROM table1,table2,table3 WHERE table1.member = table2.member AND table1.payment="fruit"
It is giving me wrong data like so:
person1 $10.00
person1 $0.00
person2 $10.00
person2 $0.00
etc
If all else fails, you could just use CSS:
tr {background-color: blue;}
tr:nth-of-type(2n) {background-color: red;}
Try doing this for a debug first:
echo "<tr class=\"alt\"> ";
My guess is that you have no data contained in your <tr> and is being squished to 0 px tall by your browser.
EDIT: I'm not entirely sure giving a class to your <tr> will filter down into the <td> based on certain browser DOM parsing. Whenever I do a zebra row, I'll assign the class to the <td>. I'm no designer by any standard, though. :)
Humor me and try this please:
$banana=0;
$view = mysql_query('SELECT ......') or die ('Encountered an error.') ;
while($rows3=mysql_fetch_array($view))
{
$total_price2=$rows3['qty']*$rows3['number'];
$banana++;
if ($banana % 2 == 0) {
$td_class = "alt";
} else {
$td_class = "";
}
echo "<tr>";
if ($total_price2!=0) {
echo "<td class='{$td_class}'>".$rows3['member']."</td>";
echo "<td class='{$td_class}'>".$rows3['payment']."</td>";
echo "<td class='{$td_class}'>$".number_format($total_price2,2)."</td>";
}
echo "</tr>";
}
That's not going to work. You're only opening the table row if $total_price2!=0. It seems you should only output the closing </tr> tag inside that IF block.
Try this instead:
<?php
$banana=0;
$view = mysql_query('SELECT ......') or die ('Encountered an error.') ;
while($rows3=mysql_fetch_array($view))
{
$total_price2=$rows3['qty']*$rows3['number'];
if ( !$total_price2)
continue;
$banana = $banana + 1;
if ($banana %2 ==0)
{
echo "<tr class=\"alt\">";
}
else
{
echo "<tr>";
}
echo "<td>".$rows3['member']."</td>";
echo "<td>".$rows3['payment']."</td>";
echo "<td>$".number_format($total_price2,2)."</td>";
echo "</tr>";
}

Categories