Shopping cart/basket session not going to database: PHP MySQL - php

I am writing a program with php/mysql in which logged in users use a points system to order items through a shopping cart (no money,paypal,credit card payments,shipping taxes etc. are involved - points only). My php knowledge is basic to low intermediate.
I have two scripts below:
The shopping cart/basket called view_cart.php
This works fine (and disables checkout if they don't have enough points).
Order submission to database called submit_order.php
I am having trouble with linking the shopping cart session to the submit order page/database. I get the first error message but it creates a new order under the orders table but only with the logged in users ID number, while the total comes to 0. Nothing happens with the order_contents table either.
I am guessing it is something to do with the 'cart' session variables/array so if someone could help or steer me in the right direction that would be great.
Thanks A
view_cart.php below:
<?php //view_cart.php
$page_title = 'ViewCart';
include ('./includes/header.html');
if (!isset($_SESSION['users_id'])) {
$url = 'http://' . $_SERVER['HTTP_HOST']
. dirname($_SERVER['PHP_SELF']);
if ((substr($url, -1) == '/') OR (substr($url, -1) == '\\') ) {
$url = substr ($url, 0, -1);
}
$url .= '/login.php';
ob_end_clean();
header("Location: $url");
exit();
}
$rwp = $_SESSION['points'];
$problem = FALSE;
if (isset($_POST['submitted']))
{
foreach ($_POST['qty'] as $k => $v) {
$pid = (int) $k;
$qty = (int) $v;
if ( $qty == 0 ) {
unset ($_SESSION['cart'][$pid]);
} elseif ( $qty > 0 ) {
$_SESSION['cart'][$pid] ['quantity'] = $qty;
}
}
}
$empty = TRUE;
if (isset ($_SESSION['cart'])) {
foreach ($_SESSION['cart'] as $key =>$value) {
if (isset($value)) {
$empty = FALSE;
break;
}
}
}
if (!$empty) {
require_once ('mysql_connect.php');
$query = "SELECT users_id, points FROM user_points
WHERE user_points.users_id = users.users_id";
$result = mysql_query($query);
$query = "SELECT products_id, products_name FROM categories, products
WHERE categories.categories_id = products.categories_id AND products.products_id
IN (";foreach ($_SESSION['cart'] as $pid =>$value) {
$query .= $pid . ',';
}
$query = substr ($query, 0, -1) . ') ORDER BY categories.categories_name ASC';
$result = mysql_query($query);
echo '
<table border="0" width="100%" cellspacing="1" cellpadding="5"
align="center">
<tr class="top">
<td align="left" width="46%"><b>Product</b></td>
<td align="right" width="18%"><b>Price</b></td>
<td align="center" width="16%"><b>Qty</b></td>
<td align="right" width="20%"><b>Sub Total</b></td>
</tr>
<form action="view_cart.php" method="post">
';
$total = 0;
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$subtotal = $_SESSION['cart'][$row
['products_id']]['quantity'] *
$_SESSION['cart'][$row ['products_id']]['price'];
$total += $subtotal;
echo " <tr>
<td align=\"left\">{$row['products_name']}</td>
<td align=\"right\">{$_SESSION['cart'][$row['products_id']] ['price']} pts</td>
<td align=\"center\"><input type=\"text\" size=\"3\"
name=\"qty[{$row['products_id']}]\"
value=\"{$_SESSION['cart'][$row['products_id']]['quantity']}\" /></td>
<td align=\"right\">" . number_format ($subtotal) . " pts</td>
</tr>\n";
}
mysql_close($dbc);
$str = '<tr class="even">
<td colspan="3" align="right"><b> TOTAL:<b></td>
<td align="right"><b>' . number_format ($total) . ' pts </b></td>
</tr>
</table>
<br />
<div align="center"><input type="submit" name="submit" value="Update" />
<input type="hidden" name="submitted" value="TRUE" />
</form><br /><br /></div>';
if($up >= $total) {
$str .='Submit Order</p>';
}
else {
$str .='<p>You do not have enough points to proceed to checkout</p>';
}
echo $str;
} else {
echo '<p>Your cart is currently empty.</p>';
}
?>
<?php
include ('./includes/footer.html');
?>
Here is the submit_order.php script.
<?php
$page_title = 'Order Confirmation';
include ('./includes/header.html');
if (!isset($_SESSION['users_id'])) {
$url = 'http://' . $_SERVER['HTTP_HOST']
. dirname($_SERVER['PHP_SELF']);
if ((substr($url, -1) == '/') OR (substr($url, -1) == '\\') ) {
$url = substr ($url, 0, -1);
}
$url .= '/login.php';
ob_end_clean();
header("Location: $url");
exit();
}
$users = $_SESSION['users_id']; // Temporary.
$total = 0;
require_once ('mysql_connect.php'); // Connect to the database.
#mysqli_autocommit ($dbc, FALSE);
$query = "INSERT INTO orders (users_id, total) VALUES
($users, $total)";
$result = #mysql_query($query);
if (#mysql_affected_rows($dbc) == 1) {
$oid = #mysql_insert_id();
$query = "INSERT INTO order_contents (order_id, products_id, quantity, price)
VALUES ";
foreach ($_SESSION['cart'] as $pid => $value) {
$query .= "($oid, $pid, {$value['quantity']}, {$value['price']})";
}
$query = substr($query, 0, -2);
$result = #mysql_query($query);
if (#mysql_affected_rows($dbc) == count($_SESSION['cart'])) {
#mysqli_commit($dbc);
#mysql_close($dbc);
unset($_SESSION['cart']);
echo '<p>Thank you for your order.
It has been submitted for processing.</p>';
} else {
#mysqli_rollback($dbc);
#mysql_close($dbc);
echo '<p>Your order could not be processed due to a system error.
You will be contacted in order to have the problem fixed.
We apologize for the inconvenience 1.</p>';
}
}
else {
#mysqli_rollback($dbc);
#mysql_close($dbc);
echo '<p>Your order could not be processed due to a system error.
You will be contacted in order to have the problem fixed.
We apologize for the inconvenience 2.</p>';
}
?>
</div></div>
<?php
include ('./includes/footer.html');
?>

I can't see
session_start();
Anywhere in here, are you calling it from a parent including file?

I guess you put session_start() in the wrong place. It must be called before the <html> tag.

Related

Updating PHP and query for displaying catergories from database php mysqli

Updating old code to php 7.3.5 and having trouble looping through a list of categories. Result should show each category available but only 1 is showing up. There are no errors.
Sample Data:
States are: South Carolina, Georgia, Illinois
Categories are: Commercial Community Development, Education, Infrastructure, Local Government, Public Buildings, Public Safety, Residential State, and Federal
Current output is:
<div style="display:inline;"> <img src="/gov_images/Residential.jpg" alt="news category Residential" border="0"> </div>
This is the old code that worked great on PHP 5...
<?php
$sql = 'SELECT * FROM state_to_category WHERE state_id="' . $state . '"';
// echo "<br> <br>Line #: " . __LINE__ . " - Select SQL: *$sql*<br>\n";
$sql_query = mysql_query($sql, $sql_link) or die("Could not select record: " . mysql_error() );
// $row_ct = mysql_num_rows($sql_query);
$state_id_list = "";
while ($row = mysql_fetch_array($sql_query))
{
$state_id_list[] = $row['cat_id'];
// echo "<br> state: " . $row['state_id'] . " cat: " . $row['cat_id'];
}
$sql = 'SELECT *
FROM news_category
WHERE type="base"
ORDER BY category';
// echo "<br> <br>Line #: " . __LINE__ . " - Select SQL: *$sql*<br>\n";
$sql_query = mysql_query($sql, $sql_link) or die("Could not select record: " . mysql_error() );
// $row_ct = mysql_num_rows($sql_query);
$category_name = "";
while ($row = mysql_fetch_array($sql_query))
{
if ($category_id == $row['id'])
{
$category_name = $row['category'];
}
$state_found = "N";
if (is_array($state_id_list))
{
foreach($state_id_list as $value)
{
if ($value == $row['id'])
{
$state_found = "Y";
}
}
}
if ($state_found == "Y")
{
?>
<div style="display:inline;">
<img src="<? echo $row['icon_small'];?>" alt="news category <? echo $row['category'];?>" border="0" />
</div>
<?php
}
}
?>
This is the same code that I'm working on updating to run on 7.3.5...
<?php
$sql = 'SELECT * FROM state_to_category WHERE state_id="' . $state . '"';
$sql_query = mysqli_query($sql_link, $sql) or die("Could not select record: " . mysqli_error() );
$state_id_list = "";
while ($row = mysqli_fetch_array($sql_query))
{
$state_id_list = array();
$state_id_list[] = $row['cat_id'];
}
$sql = 'SELECT *
FROM news_category
WHERE type="base"
ORDER BY category';
$sql_query = mysqli_query($sql_link, $sql) or die("Could not select record: " . mysqli_error() );
$category_name = "";
while ($row = mysqli_fetch_array($sql_query))
{
if ($category_id == $row['id'])
{
$category_name = $row['category'];
}
$state_found = "N";
if (is_array($state_id_list))
{
foreach($state_id_list as $value)
{
if ($value == $row['id'])
{
$state_found = "Y";
}
}
}
if ($state_found == "Y")
{
?>
<div style="display:inline;">
<img src="<? echo $row['icon_small'];?>" alt="news category <? echo $row['category'];?>" border="0" />
</div>
<?php
}
}
?>
Any help is greatly appreciated!
I had the same problem updating at the same time the sql injection came up so i updated all my querys and loops and worked great
using PDO conector:
$mysql_pdo = new PDO("mysql:host=localhost;dbname=DATABASE","user", "passwd");
$query_categories = 'SELECT *
FROM news_category
WHERE type=:type
ORDER BY category';
$Q_categories = $mysql_pdo->prepare($query_categories);
$Q_categories->bindParam(':type',"base");
$Q_categories->execute();
while($row = $Q_categories->fetch())
{
if ($category_id == $row['id']) **<--maybe you lost $category_id on the update?**
{
$category_name = $row['category'];
}
$state_found = "N";
if (is_array($state_id_list))
{
foreach($state_id_list as $value)
{
if ($value == $row['id'])
{
$state_found = "Y";
}
}
}
if ($state_found == "Y")
{
?>
<div style="display:inline;">
<img src="<? echo $row['icon_small'];?>" alt="news category <? echo $row['category'];?>" border="0" />
</div>
<?php
}
}
in this way you prepare your code for further updates and secure it against sql inyection mysqli_query is depecrated maybe thats why you are getting erratic behavior

Hyperlink to another page is not working

When I click on Add to cart hyperlink, cart.php page is not responding (it's not echoing the add variable. Hyperlink looks fine. However, there is something wrong in cart.php. Any response is appreciated. Thanks in advance.
<html>
<head>
</head>
<body>
<table>
<tr>
<td><?php echo $row['ISBN']; ?></td>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['title']; ?></td>
<td><?php echo $row['year']; ?></td>
<td><?php echo $row['price']; ?></td>
<td><?php echo $row['publisher']; ?></td>
<td> Add to cart</td>
<td><?php echo $row['ISBN']; ?></td>
</tr>
</table>
</body>
</html>
cart.php page:
<?php
//
session_start();
$page = 'search.php';
$lpage = 'cart.php';
$db = new mysqli('localhost', 'root', '', 'cheapbook') or die('Error connecting to MySQL server.');
mysqli_set_charset($db, 'utf8');
if (isset($_GET['add'])) {
echo $_GET['add'];
$pieces = explode(":", $_GET['add']);
$quantity = mysqli_query('SELECT ISBN, title from book WHERE ISBN=$pieces[0]');
$result = mysqli_query($db, $quantity);
while ($quantity_row = mysqli_fetch_array($result)) {
if ($quantity_row['quantity'] != $_SESSION['cart_' . $_GET['add']]) {
$_SESSION['cart_' . $_GET['add']] += 1;
}
}
if ($pieces[1] == 'SearchByBookTitle') {
header('location:' . $page . 'SearchByBookTitle=' . $pieces[2]);
}
if ($pieces[1] == 'SearchByAuthor') {
header('location:' . $page . 'SearchByAuthor=' . $pieces[2]);
echo $pieces[1];
} else {
header('location:' . $lpage);
}
}
if (isset($_GET['remove'])) {
$_SESSION['cart_' . $_GET['remove']]--;
header('location:' . $page);
}
if (isset($_GET['delete'])) {
$_SESSION['cart_' . $_GET['remove']]--;
header('location:' . $page);
}
if (isset($_GET['cart'])) {
cart();
}
function cart()
{
foreach ($_SESSION as $name => $value) {
if ($value > 0) {
if (substr($name, 0, 5) == 'curt_') {
$total = 0;
$id = substr($name, 5, (strlen($name) - 5));
$get = mysql_query("SELECT ISBN, title, price FROM book where id='.$id.'");
$result = mysqli_query($db, $get);
while ($get_row = mysqli_fetch_array($result)) {
$sub = $get_row['price'] * $value;
echo $get_row['title'] . 'X' . $value . '#Dollar' . $get_row['price'] . '=' . $sub . '[-][+][Delete]';
}
$total += $sub;
}
}
if ($total == 0) {
echo "Your cart is empty";
} else {
echo "Paypal button";
}
}
}
?>
This query coded like this of course will not work as expected
$quantity = mysqli_query('SELECT ISBN, title
from book
WHERE ISBN=$pieces[0]');
You need a double quoted string to use variable expansion, it does not work in a single quoted string.
You also need to add single quotes around the text varibale parameter value
$quantity = mysqli_query("SELECT ISBN, title
from book
WHERE ISBN='$pieces[0]'");
In future you would be well advised to add some error checking code after you attempt to execute a query and also use prepared and parameterised queries to avoid SQL Injection
$sql = "SELECT ISBN, title from book WHERE ISBN=?";
$stmt = mysqli_prepare($sql);
if ( ! $stmt ) {
echo mysqli_error();
exit;
}
$stmt->bind_param('s', $pieces[0] );
$stmt->execute();

PHP if statement - Resource id issue

I have some code below which retrieves data from a table named "tally_point"
What I am trying to is retrieve a value from a column named 'tpt_id'
On another table, there is a table named "tally_point_type", which has has the primary key 'tpt_id' as well.
What I am trying to do is get the 'tpt_name' value to print from the tally_point_type row. At the moment I can get the "Order Details" link to work but the $tpt_name value prints out a Resource id# value.
I knwo Im close but can't quite figure out how to get this to work.
<?php
$pointstype = $row['tpt_id'];
$type = '<td align="center">';
if($pointstype > '0') {
$query = "SELECT tpt_name
FROM tally_point_type
WHERE'" . $row['tpt_id'] . "'=$pointstype";
$tpt_name = mysql_query($query);
$type .='<strong>' . $tpt_name . '</strong></td></tr>';
}
else {
$type .='<strong>Order Details</strong></td></tr>';
}
echo $type;
?>
Full code here:
<?php # index.php
require_once ('./includes/config.inc.php');
$page_title = 'Title';
include ('includes/header.html');
if (!isset($_SESSION['admin_int_id'])) {
$url = 'http://' . $_SERVER['HTTP_HOST']
. dirname($_SERVER['PHP_SELF']);
// Check for a trailing slash.
if ((substr($url, -1) == '/') OR (substr($url, -1) == '\\') ) {
$url = substr ($url, 0, -1); // Chop off the slash.
}
$url .= '/login.php';
ob_end_clean(); // Delete the buffer.
header("Location: $url");
exit(); // Quit the script.
}
if ( (isset($_GET['id'])) && (is_numeric($_GET['id'])) )
{ // Accessed through view_users.php
$id = $_GET['id'];
} elseif ( (isset($_POST['id'])) && (is_numeric($_POST['id'])) )
{ // Form has been submitted.
$id = $_POST['id'];
} else { // No valid ID, kill the script.
echo '<h1 id="mainhead">Page Error</h1>
<p class="error">This page has been accessed in error.</p><p><br /><br /></p>';
include ('./includes/header.html');
exit();
}
require_once ('/database.php'); // Connect to the db.
$display = 1000;
if (isset($_GET['np'])) { // Already been determined.
$num_pages = $_GET['np'];
} else { // Need to determine.
$query = "SELECT COUNT(*) FROM tally_point, users WHERE tally_point.users_id = users.users_id ORDER BY tally_points_entry_date DESC";
$result = #mysql_query ($query);
$row = #mysql_fetch_array ($result, MYSQL_NUM);
$num_records = $row[0];
if ($num_records > $display) { // More than 1 page.
$num_pages = ceil($num_records/$display);
} else {
$num_pages = 1;
}
}
if (isset($_GET['s'])) {
$start = $_GET['s'];
} else {
$start = 0;
}
$link1 = "{$_SERVER['PHP_SELF']}?sort=lna";
$link2 = "{$_SERVER['PHP_SELF']}?sort=fna";
$link3 = "{$_SERVER['PHP_SELF']}?sort=dra";
if (isset($_GET['sort'])) {
switch ($_GET['sort']) {
case 'lna':
$order_by = 'tally_points_in ASC';
$link1 = "{$_SERVER['PHP_SELF']}?sort=lnd";
break;
case 'lnd':
$order_by = 'tally_points_in DESC';
$link1 = "{$_SERVER['PHP_SELF']}?sort=lna";
break;
case 'fna':
$order_by = 'total ASC';
$link2 = "{$_SERVER['PHP_SELF']}?sort=fnd";
break;
case 'fnd':
$order_by = 'total DESC';
$link2 = "{$_SERVER['PHP_SELF']}?sort=fna";
break;
case 'dra':
$order_by = 'tally_points_entry_date ASC';
$link3 = "{$_SERVER['PHP_SELF']}?sort=drd";
break;
case 'drd':
$order_by = 'tally_points_entry_date DESC';
$link3 = "{$_SERVER['PHP_SELF']}?sort=dra";
break;
default:
$order_by = 'tally_points_entry_date DESC';
break;
}
$sort = $_GET['sort'];
} else { // Use the default sorting order.
$order_by = 'tally_points_entry_date DESC';
$sort = 'dra';
}
$query = "SELECT ta.tally_points_in, ta.order_id, ta.total, ta.tpt_id , DATE_FORMAT(ta.tally_points_entry_date, '%d-%m-%Y') AS dr, ta.users_id
FROM tally_point AS ta
WHERE ta.users_id=$id
ORDER BY
".$order_by." LIMIT ".$start.", ".$display;
$result = #mysql_query ($query); // Run the query.
echo '
<table width="500" cellspacing="1" cellpadding="7">
<tr class="top">
<td align="left"><b>Date</b></td>
<td align="center"><b>Credit</b></td>
<td align="center"><b>Debit</b></td>
<td align="center"><b>Description</b></td>
</tr>
';
$bg = '#ffffff'; // Set the background color.
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$pointsitem = $row['order_id'];
$pointstype = $row['tpt_id'];
$bg = ($bg=='#eaeced' ? '#ffffff' : '#eaeced'); // Switch the background color.
//$entries = floor($row['ltd_entry_amount']/200);
echo '<tr bgcolor="' . $bg . '">';
echo '<td align="left">' . $row['dr'] . '</td>';
echo '<td align="center"><strong>' . $row['tally_points_in'] . '</strong></td> ';
echo '<td align="center">' . $row['total'] . '</td>';
$type = '<td align="center">';
if($pointstype > '0') {
$query = "SELECT tpt_name
FROM tally_point_type
WHERE'" . $row['tpt_id'] . "'=$pointstype"; //THIS ALSO SEEMS WRONG column name should have backticks if you're trying to escape it and maybe value should be quoted? Also these values are the same, no?
$result = mysql_query($query);
$tpt_name = mysql_fetch_assoc($result);
$type .='<strong>' . $tpt_name['tpt_name'] . '</strong></td></tr>';
} else {
$type .='<strong>Order Details</strong></td></tr>';
}
echo $type;
}
echo '</table>';
mysql_free_result ($result); // Free up the resources.
mysql_close(); // Close the database connection.
if ($num_pages > 1) {
echo '<br /><p>';
$current_page = ($start/$display) + 1;
if ($current_page != 1) {
echo '<a href="view_points_2.php?s=' . ($start - $display) . '&np=' .
$num_pages . '&sort=' . $sort .'">Previous</a> ';
}
for ($i = 1; $i <= $num_pages; $i++) {
if ($i != $current_page) {
echo '<a href="view_points_2.php?s=' . (($display * ($i - 1))) .
'&np=' . $num_pages . '&sort=' . $sort .'">' . $i . '</a> ';
} else {
echo $i . ' ';
}
}
if ($current_page != $num_pages) {
echo '<a href="view_points_2.php?s=' . ($start + $display) . '&np=' .
$num_pages . '&sort=' . $sort .'">Next</a> ';
}
echo '</p>';
}
include ('./includes/footer.html'); // Include the HTML footer.
?>
You need to fetch the result.
<?php
$pointstype = $row['tpt_id'];
$type = '<td align="center">';
if($pointstype > '0') {
$query = "SELECT tpt_name
FROM tally_point_type
WHERE'" . $row['tpt_id'] . "'=$pointstype"; //THIS ALSO SEEMS WRONG column name should have backticks if you're trying to escape it and maybe value should be quoted? Also these values are the same, no?
$result = mysql_query($query);
$tpt_name = mysql_fetch_assoc($result);
$type .='<strong>' . $tpt_name['tpt_name'] . '</strong></td></tr>';
} else {
$type .='<strong>Order Details</strong></td></tr>';
}
echo $type;
?>
Also see notes in the comment of your query, consider switching drivers to mysqli or PDO, and I'm not sure about where the data you're using is coming from but might be open to a SQL injection. How can I prevent SQL injection in PHP?
Here's the manual link for future reference http://php.net/manual/en/function.mysql-query.php. See example #2.
You need to fetch the result:
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$tpt_name = $row['tpt_name'];

Value of variable is not stored correctly while transfering the value from HTML form to PHP file

Thanks Ben, but now the other issue that I am facing is that result is not being displayed first time when I add the pagination to the code. See the second half of the code below. Please help
if(isset($_GET['k'])){ $k1 = $_GET['k']; } else { $k1 = ''; }
echo $k1;
$term = explode(" ", $k1);
$query = "SELECT * FROM database ";
foreach ($term as $each)
{
echo $each;
$i++;
if($i==1)
{
$query .= "WHERE keywords LIKE '%$each%' ";
}
else {
$query .= "OR WHERE keywords LIKE '%$each%' ";
}
}
$per_pages=3;
$page_query = mysql_query("SELECT COUNT('title') FROM kcpdatabase");
$pages = ceil(mysql_result($page_query, 0)/$per_pages) or die
($page_query."<br/><br/>".mysql_error());
$page = (isset($_GET['page'])) ? (int)
($_GET['page']) : 1;
$start = ($page - 1) * $per_pages;
$query .= "LIMIT $start, $per_pages";
$ourquery1 = mysql_query ($query);
if(!$ourquery1)
echo "No query found";
$row1 = mysql_num_rows ($ourquery1);
if($pages >= 1 && $page <= $pages){
for($x = 1; $x <= $pages; $x++)
{
echo ''.$x.' ';
}
if ($row1 > 0)
{
while($result = mysql_fetch_assoc($ourquery1))
{
echo "<tr>";
echo "<td>";
$title = $result['title'];
$link = $result['link'];
$region = $result['region'];
$sector = $result['sector'];
$theme = $result['theme'];
echo "<td> <a href=$link><h3>$title<h3></a>";
echo "<h4>Sector: $sector <br>Theme: $theme <br> Region: $region
</td> </tr>";
}
}
}
echo "</tbody>";
Below is a portion of my code where I am trying to search a word/ phrase entered in the text box. When I catch the value from the form in a php file using "$k1 = isset($_GET['k']);" the value which get's stored in variable "$each" is "1" and NOT the word or phrase entered by the user. This messess up the query which is performing the search function. Please help me to locate the error.
Please note that 'k' is the name of text box as defined in the form code below.
<form name="keywordquery" method="get" action="page2.php">
<fieldset class="fieldsetclass"><legend class="legendclass">Search by Keywords</legend>
<div id="searchbox">
<input type="text" name="k" value="<?php if(isset($_GET['k'])){echo htmlentities($_GET
['k']);} ?>" style="border: 1px, thin; width:92%; "/>
<input type="image" style="margin-bottom: 0; margin-top: 2px;" src="search.png"
value="submit" />
</div>
</fieldset>
</form>
</div>
<table cellpadding="0" cellspacing="0" border="1">
<tbody>
<?php
$connection = mysql_connect('', '', '');
if(!$connection)
echo "No database connected";
$dbase = mysql_select_db("", $connection);
if(!$dbase)
echo "No datatable connected";
$k1 = isset($_GET['k']);
echo $k1;
$term = explode(" ", $k1);
$query = "SELECT * FROM datatable ";
foreach ($term as $each)
{
echo $each;
$i++;
if($i==1)
{
$query .= "WHERE keywords LIKE '%$each%' ";
}
else {
$query .= "OR WHERE keywords LIKE '%$each%' ";
}
}
$k1 = isset($_GET['k']);
It's setting $k1 as 1 as it's ckecking to see if it's been set - in this case it has been and isset() is returning true, or 1.
what you want is:
if(isset($_GET['k'])){ $k1 = $_GET['k']; } else { $k1 = ''; }
or similar.
Thats because isset() is a bool function, check following link http://php.net/manual/en/function.isset.php
just do this
if(isset($_GET['k']))
$k1 = $_GET['k'];

SELECT COUNT and Undefined offset issue

I'm having trouble trying to print a first name and surname for this SELECT COUNT (*) page below. If I delete the code which says "' . $row[6] . ' ' . $row[7] . '" the page works fine and prints the selected user's tally points rows only but not their first name and surname. I get the message below if I dont delete this code:
*
An error occurred in script 'database.php' on line 177: Undefined offset: 6 Date/Time: 3-8-2012 12:27:03
*
<?php # index.php
// Include the configuration file for error management and such.
require_once ('./includes/config.inc.php');
// Set the page title and include the HTML header.
$page_title = 'Individual Member Transactions';
include ('includes/header_admin_user.html');
// If no dealer_code variable exists, redirect the user.
if (!isset($_SESSION['admin_int_id'])) {
// Start defining the URL.
$url = 'http://' . $_SERVER['HTTP_HOST']
. dirname($_SERVER['PHP_SELF']);
// Check for a trailing slash.
if ((substr($url, -1) == '/') OR (substr($url, -1) == '\\') ) {
$url = substr ($url, 0, -1); // Chop off the slash.
}
// Add the page.
$url .= '/login.php';
ob_end_clean(); // Delete the buffer.
header("Location: $url");
exit(); // Quit the script.
}
// Check for a valid user ID, through GET or POST.
if ( (isset($_GET['id'])) && (is_numeric($_GET['id'])) )
{ // Accessed through view_users.php
$id = $_GET['id'];
} elseif ( (isset($_POST['id'])) && (is_numeric($_POST['id'])) )
{ // Form has been submitted.
$id = $_POST['id'];
} else { // No valid ID, kill the script.
echo '<h1 id="mainhead">Page Error</h1>
<p class="error">This page has been accessed in error.</p><p><br /><br /></p>';
include ('./includes/header_admin_user.html');
exit();
}
?>
<h1 id="mainhead">Points Transactions</h1>
<div id="sidebar">
<div id="statusbar">
<p><span class="statusbar_highlight">Name:</span><br />
<?php echo " {$_SESSION['adminfirstname']} " . " {$_SESSION['adminsurname']}<br> ";?></p>
<p><span class="statusbar_highlight">Status:</span><br />
<?php echo " {$_SESSION['adminstatus']} ";?></p>
<p><span class="statusbar_highlight">Employer:</span><br />
<?php echo " {$_SESSION['adminemployer']} ";?></p>
</div>
</div>
<div id="maincontent_results">
<?php
require_once ('database.php'); // Connect to the db.
// Number of records to show per page:
$display = 1000;
// Determine how many pages there are.
if (isset($_GET['np'])) { // Already been determined.
$num_pages = $_GET['np'];
} else { // Need to determine.
// Count the number of records
$query = "SELECT COUNT(*) FROM tally_point, users WHERE tally_point.users_id = users.users_id ORDER BY tally_points_entry_date DESC";
$result = #mysql_query ($query);
$row = #mysql_fetch_array ($result, MYSQL_NUM);
$num_records = $row[0];
// Calculate the number of pages.
if ($num_records > $display) { // More than 1 page.
$num_pages = ceil($num_records/$display);
} else {
$num_pages = 1;
}
} // End of np IF.
// Determine where in the database to start returning results.
if (isset($_GET['s'])) {
$start = $_GET['s'];
} else {
$start = 0;
}
// Default column links.
$link1 = "{$_SERVER['PHP_SELF']}?sort=lna";
$link2 = "{$_SERVER['PHP_SELF']}?sort=fna";
$link3 = "{$_SERVER['PHP_SELF']}?sort=dra";
// Determine the sorting order.
if (isset($_GET['sort'])) {
// Use existing sorting order.
switch ($_GET['sort']) {
case 'lna':
$order_by = 'tally_points_in ASC';
$link1 = "{$_SERVER['PHP_SELF']}?sort=lnd";
break;
case 'lnd':
$order_by = 'tally_points_in DESC';
$link1 = "{$_SERVER['PHP_SELF']}?sort=lna";
break;
case 'fna':
$order_by = 'total ASC';
$link2 = "{$_SERVER['PHP_SELF']}?sort=fnd";
break;
case 'fnd':
$order_by = 'total DESC';
$link2 = "{$_SERVER['PHP_SELF']}?sort=fna";
break;
case 'dra':
$order_by = 'tally_points_entry_date ASC';
$link3 = "{$_SERVER['PHP_SELF']}?sort=drd";
break;
case 'drd':
$order_by = 'tally_points_entry_date DESC';
$link3 = "{$_SERVER['PHP_SELF']}?sort=dra";
break;
default:
$order_by = 'tally_points_entry_date DESC';
break;
}
// $sort will be appended to the pagination links.
$sort = $_GET['sort'];
} else { // Use the default sorting order.
$order_by = 'tally_points_entry_date DESC';
$sort = 'dra';
}
// Select tally rows for the selected user and the users details
$query = "SELECT ta.tally_points_in, ta.order_id, ta.total, DATE_FORMAT(ta.tally_points_entry_date, '%d-%m-%Y') AS dr, ta.users_id, us.users_id, us.users_first_name, us.users_surname
FROM tally_point AS ta, users AS us
WHERE ta.users_id=$id
AND us.users_id = ta.users_id
ORDER BY
".$order_by." LIMIT ".$start.", ".$display;
$result = #mysql_query ($query);
// Table header.
echo ' ' . $row[6] . ' ' . $row[7] . '
<table width="400" cellspacing="1" cellpadding="7">
<tr class="top">
<td align="left"><b>Date</b></td>
<td align="center"><b>Credit</b></td>
<td align="center"><b>Debit</b></td>
<td align="center"><b>Description</b></td>
</tr>
';
// Fetch and print all the transactions.
$bg = '#ffffff'; // Set the background color.
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$pointsitem = $row['order_id'];
$bg = ($bg=='#eaeced' ? '#ffffff' : '#eaeced'); // Switch the background color.
//$entries = floor($row['ltd_entry_amount']/200);
echo '<tr bgcolor="' . $bg . '">';
echo '<td align="left">' . $row['dr'] . '</td>';
echo '<td align="center"><strong>' . $row['tally_points_in'] . '</strong></td> ';
echo '<td align="center">' . $row['total'] . '</td>';
// products the footer, close the table, and the form.
$str = '<td align="center">';
if($pointsitem > '0') {
$str .='<strong>Order Details</strong></td></tr>';
}
else {
$str .='Monthly Points Update</td></tr>';
}
echo $str;
}
echo '</table>';
mysql_free_result ($result); // Free up the resources.
mysql_close(); // Close the database connection.
// Make the links to other pages, if necessary.
if ($num_pages > 1) {
echo '<br /><p>';
// Determine what page the script is on.
$current_page = ($start/$display) + 1;
// If it's not the first page, make a Previous button.
if ($current_page != 1) {
echo '<a href="view_points_2.php?s=' . ($start - $display) . '&np=' .
$num_pages . '&sort=' . $sort .'">Previous</a> ';
}
// Make all the numbered pages.
for ($i = 1; $i <= $num_pages; $i++) {
if ($i != $current_page) {
echo '<a href="view_points_2.php?s=' . (($display * ($i - 1))) .
'&np=' . $num_pages . '&sort=' . $sort .'">' . $i . '</a> ';
} else {
echo $i . ' ';
}
}
// If it's not the last page, make a Next button.
if ($current_page != $num_pages) {
echo '<a href="view_points_2.php?s=' . ($start + $display) . '&np=' .
$num_pages . '&sort=' . $sort .'">Next</a> ';
}
echo '</p>';
} // End of links section.
?>
<br class="clearboth" />
</div>
</div>
</div>
<?php
include ('./includes/footer_admin_user.html'); // Include the HTML footer.
?>
You would need to do:
$row = #mysql_fetch_array ($result, MYSQL_NUM);
on the line before the error.
Right now it is throwing you an error because the last time you set $row was in this piece of code on the top:
// Count the number of records
$query = "SELECT COUNT(*) FROM tally_point, users WHERE tally_point.users_id = users.users_id ORDER BY tally_points_entry_date DESC";
$result = #mysql_query ($query);
$row = #mysql_fetch_array ($result, MYSQL_NUM);
In this context $row only has one element ($row[0]).

Categories