MySQL search and data output

Started by mariajones, Sep 09, 2022, 01:07 AM

Previous topic - Next topic

mariajonesTopic starter

Hi! The database stores surnames and first names. The user enters his first and last name into the form and, if they are in the database, the feedback of that user is displayed. Here's what I've been collecting from various sources, but unfortunately it doesn't work. Please help me.

<form method="POST" action="<?= $_SERVER['SCRIPT_NAME'] ?>">
   <input name="name" type='text' placeholder="Name"/>
   <input name="surname" type='text' placeholder="surname"/>
   <textarea name="feedback" cols=40 rows=10 placeholder="Feedback"/></textarea>
   <input type="submit" value="Submit"/>
  </form>

$db_host = "localhost";
$db_user = "root"; // Database login
$db_password = "root"; // Database password
$db_base = 'enot'; // Database name
$db_table = "enot_2"; // Database table name
$mysqli = new mysqli($db_host, $db_user, $db_password, $db_base);
 
if (isset($_POST['name']) && (isset($_POST['surname'])) && isset($_POST['feedback'])){
  // Variables from the form
  $name = $_POST['name'];
  $surname = $_POST['surname'];
  $feedback = $_POST['feedback'];
 
  // Parameters for connection
 
  $inputSearch = $_REQUEST['search'];
 
  // Create SQL query
  $sql = "SELECT * FROM `enot_2` WHERE `name` = '$inputSearch' || `surname` = '$inputSearch'";
 
// Send SQL query
  $result = $mysqli -> query($sql);
 
function doesItExist(array $arr) {
    // Create a new array
    $data = array(
        'name' => $arr['name'] != false ? $arr['name'] : 'No data',
        'surname' => $arr['surname'] != false ? $arr['surname'] : 'No data'
    );
    return $data; // Return this array
}
  function countPeople($result) {
    // Check if strings are greater than zero
    if ($result -> num_rows >0) {
        // Loop to output data
        while ($row = $result -> fetch_assoc()) {
            // Get an array with strings to be output
            $arr = doesItExist($row);
            // Data output
            echo
                  "Name: ". $row['name'] ."<br>
                  Last name: ". $row['surname'] ."<br>
                  Feedback: ". $row['feedback'] ."<br>"
                 ;
        }
    // If there is no data
    } else {
        echo "Invalid data entered";
          }
  }
 
  countPeople($result);
  •  

kpripper

Before php 8.0, by default, pdo will not throw exceptions or warnings for errors. You need to turn it on yourself.

$db = new PDO("mysql:host=$db_host;dbname=$db_base", $db_user, $db_password, [
      PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);
  •