Well, doing a beginner project. I've 100% finished with adding items to the DB. However, having stuck trying to use the "search" button to retrieve the DB list, as well updating errors.

Objective, input last name, click on search, and find the results based on the last name input. Here's what I have so far.
search.php

<?php include '../view/header.php'; ?>
<div id="main">

    <h1>Customer Search</h1>
    
    <div id="content">
        <!-- display a table of products -->
       
<form  method="post" action="index.php"  id="search_form">  
   <label>Last Name:</label>
<input  type="text" name="lastName">  
<input  type="submit" value="Search">  

</form>
         <table>
     
                <tr>
                <th>last Name</th>
                <th>email</th>
                <th class="right">city</th>
                <th>phone</th>

                <th>&nbsp;</th>
            </tr>
             <?php foreach ($customers as $customer) : ?>
             <tr>
                 <td><?php echo $customer['lastName']; ?></td>
                 <td><?php echo $customer['email']; ?></td>
                 <td class="right"><?php echo $customer['city']; ?></td>
                 <td><?php echo $customer['phone']; ?></td>
                 <td><form action="." method="post">
                     <input type="hidden" name="action"
                            value="update_customer" />
                     <input type="hidden" name="customerID"
                            value="<?php echo $customer['customerID']; ?>" />
 
                     <input type="submit" value="Select" />
                 </form></td>
             </tr>
             <?php endforeach; ?>
        </table>
 
  
    </div>
</div>
<?php include '../view/footer.php'; ?>

Line 1-14 has it's own php, the "customer_list.php" where it just shows the search bar. after clicking on it, it gets to my search.php. that's where I get errors. Undefined variable: customers line 25. And Invalid argument supplied for foreach()

Anyhelp is appreciated to the right direction. Just need guidance to get to the right step. I may have to tweak my index.php/customer_db.php.

$customers is never assigned a value, unless some code is missing.

My customer_db.php. Didn't want an 1 post be some long/huge php codes

<?php
function get_customers() {
    global $db;
    $query = 'SELECT * FROM customers
              ORDER BY customerID';
    $customers = $db->query($query);
    return $customers;
}

function get_customer($customerID) {
    global $db;
    $query = "SELECT * FROM customers
              WHERE customerID = '$customerID'";  //previously "productCode"
    $customer = $db->query($query);
    $customer = $customer->fetch();
    return $customer;
}

function update_customer($firstName, $lastName, $address, $city, $state,
        $postalCode, $countryCode, $phone, $email, $password) {
    global $db;
    $query = "UPDATE customers
              SET lastName = $lastName
              WHERE customerID = $customerID";
    $db->exec($query);
}
?>

Er last php code post, sorry for overdoing it, my index.php. It's probably the root to my problems now that i'm tweaking it.

<?php
require('../model/database.php');
 require('../model/customer_db.php');

if (isset($_POST['action'])) {
    $action = $_POST['action'];
} else if (isset($_GET['action'])) {
    $action = $_GET['action'];
} else {
    $action = 'list_customers';
}

if ($action == 'list_customers') {

    $customers = get_customers();
    // Display the customer list
    include('customer_list.php');


} else if ($action == 'search_form') {
  $customers = get_customers();
    $lastName = $_GET['lastName'];
    include('search.php');
   } else if ($action == 'update_customer') {
       $firstName= $_GET['firstName'];
       $lastName = $_GET['lastName'];
       $address = $_GET['address'];
       $city = $_GET['city'];
       $state = $_GET['state'];
       $postalCode = $_GET['postalCode'];
       $countryCode = $_GET['countryCode'];
       $phone = $_GET['phone'];
       $email = $_GET['email'];
       $password = $_GET['password'];
       // Validate the inputs
    
       if (empty($firstName) || empty($lastName)  ||  empty($address) || empty($city)  || empty($state) 
               ||  empty($postalCode)  ||  empty($countryCode)  ||  empty($phone)  ||  empty($email)  ||  empty($password)) {
           $error = "Invalid product data. Check all fields and try again.";
           include('../errors/error.php');
       } else {
           update_customer($firstName, $lastName, $address, $city, $state,
                $postalCode, $countryCode, $phone, $email, $password); 
    // display the Category List page
header("Location: .?category_id=$category_id");
    }
   }
   ?>

If (somewhere in your search.php before the foreach) you do print_r($customers); what does it output ?

If (somewhere in your search.php before the foreach) you do print_r($customers); what does it output ?

Sorry for the late reply. Was talking to some fellow classmates about this, and we're just stumped a bit, so we're going to have to stay after class for some help. However, I improved it a bit... (P.s) - it only output "print_r(customers) :P

Here's my revised program. lines 1-14 is already in "index.php" just copy and pasted to the search.php. This is my revised Search.php. Here's my problem. When I click "Search", it gets ALL the names. What i'm trying to do is just get the name I input to show up only. So if I input "Smith", it'll show two names with Smith, but rather it just shows me all the names. Therefore, a little help on how I can fix this. Here is my code.

<?php include '../view/header.php'; ?>
<?php require('../model/database.php');
 require('../model/customer_db.php'); ?>
<div id="main">

    <h1>Customer Search</h1>
    
    <div id="content">
        <!-- display a table of products -->
       
<form  method="post" action="search.php?go" id ="searchform"> 
<label>Last Name:</label>
<input  type="text" name="lastName">  
<input  type="submit" name ="submit" value="Search">  
</form>
        
<?php
if(isset($_POST['submit'])) {
  if(isset($_GET['go'])) {  
      if(preg_match("/^[A-za-z]+/", $_POST['lastName'])){
          //connect
          $db = mysql_connect("localhost", "username", "password") or die ('I cannot connect to the database  because: ' . mysql_error());
          
          //select
          $mydb=mysql_select_db("dbname");
          
          //
          $sql = "SELECT * FROM customers"; //my tablename "customers"
          
          //run
          $result = mysql_query($sql);
          $name=$_POST['lastName'];
         

     
     
     //Create a while loop
     while ($row = mysql_fetch_array($result)){
         $lastName = $row['lastName'];
         $firstName = $row['firstName'];
         $email = $row['email'];
         $city = $row['city'];
         
         //display
          echo "<tr> <th>Last Name,</th> <th>First Name</th> <th>Email</th> <th>City</th> <th></th></tr>";


         echo "<u1>\n";
echo "<li>" . "<a  href=\"search.php?id=$row\">"   .$lastName . " " . $firstName . " " .  $email  . " " .  $city  . "</li>\n"; 
  echo "</ul>"; 
  
        } 

        // close table>
        echo "</table>";

}
          }
}
else
{
    echo "<p>Please input a valid name</p>";

}
    ?>
}

    </div>
</div>
<?php include '../view/footer.php'; ?>

Ok that's pretty much it. I revised it by brainstorming with others. so it gets all the names. Also, the "last name, first name, city, email" echo table, inputs each time a name is called. Alrighty, so just any pointers on how I should fix this is much appreciated.

If you want to get from the database only the customers whose last name matches what was input then you have to modify line 28 and write

$sql= sprintf("SELECT * FROM customers where lastName='%s'",mysql_real_escape_string($_POST['lastName'])); //my tablename "customers"

You could also use the following code to find all customer whose last name begins with what was input:

$sql= sprintf("SELECT * FROM customers where lastName like '%s%%'",mysql_real_escape_string($_POST['lastName'])); //my tablename "customers"

To display the data found by the query:

// open HTML <table>
echo "<table>";
echo "<tr> <th>Last Name,</th> <th>First Name</th> <th>Email</th> <th>City</th> <th></th></tr>";

//Loop through all customers 
while ($row = mysql_fetch_array($result))
{ 
//display
echo "<tr> <td>".$row['lastName']."</td><td>".$row['firstName']."</td> <td>".$row['email']."</td> <td>".$row['city']."</td> <td></td></tr>";
}
// close table>
echo "</table>";

The idea is to put OUTSIDE the loop everything that needs to be displayed only once and INSIDE the loop only the text that will be repeated.

Hope this helps.

If you want to get from the database only the customers whose last name matches what was input then you have to modify line 28 and write

$sql= sprintf("SELECT * FROM customers where lastName='%s'",mysql_real_escape_string($_POST['lastName'])); //my tablename "customers"

You could also use the following code to find all customer whose last name begins with what was input:

$sql= sprintf("SELECT * FROM customers where lastName like '%s%%'",mysql_real_escape_string($_POST['lastName'])); //my tablename "customers"

To display the data found by the query:

Thanks.  I have solved it :)  much appreciated, can now get the last names correctly!
// open HTML <table>
echo "<table>";
echo "<tr> <th>Last Name,</th> <th>First Name</th> <th>Email</th> <th>City</th> <th></th></tr>";

//Loop through all customers 
while ($row = mysql_fetch_array($result))
{ 
//display
echo "<tr> <td>".$row['lastName']."</td><td>".$row['firstName']."</td> <td>".$row['email']."</td> <td>".$row['city']."</td> <td></td></tr>";
}
// close table>
echo "</table>";

The idea is to put OUTSIDE the loop everything that needs to be displayed only once and INSIDE the loop only the text that will be repeated.

Hope this helps.

Thanks! I have solved it now, much appreciated. Can now get the last names correctly. Thanks :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.