If you like DNray Forum, you can support it by - BTC: bc1qppjcl3c2cyjazy6lepmrv3fh6ke9mxs7zpfky0 , TRC20 and more...

 

MySQL search

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

Previous topic - Next topic

mariajonesTopic starter

Hello there! The database is used to store the names and surnames of users. If a user enters their first and last name correctly into the form, their feedback will be displayed. However, I have collected this code from various sources and unfortunately, it doesn't work. Can you help me out?

<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'])){

  // Store the variables that we get from the form
  $name = $_POST['name'];
  $surname = $_POST['surname'];
  $feedback = $_POST['feedback'];

  // Set 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 this array
    return $data;
  }
 
  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);
           
            // Output the data
            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);

The code above is used to collect user feedback by storing their names and surnames in a database. If the user enters their name and surname correctly, the feedback will be displayed. Unfortunately, this code doesn't seem to work as intended. Do you have any suggestions on how to fix it?
  •  

kpripper

Prior to PHP 8.0, default settings in PDO would not generate exceptions or warnings for errors. Therefore, enabling it is necessary.

Here is an example code that can be used to enable these settings:

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

By adding the `PDO::ATTR_ERRMODE` setting and setting it to `PDO::ERRMODE_EXCEPTION`, you can turn on exceptions and warnings for errors. This can help with debugging and troubleshooting any issues that may arise in the future.
  •  

fallfro

There are a few issues with the code you provided. Here are some suggestions to fix them:

1. Make sure you have a database connection established before running any queries. You can modify your code like this:

```php
// Create the database connection
$mysqli = new mysqli($db_host, $db_user, $db_password, $db_base);

// Check if the connection was successful
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: " . $mysqli->connect_error;
    exit();
}
```

2. Ensure that the input variables are properly escaped to prevent SQL injection. You can use prepared statements to achieve this. Modify your code like this:

```php
// Create a prepared statement
$stmt = $mysqli->prepare("SELECT * FROM enot_2 WHERE name = ? OR surname = ?");
$stmt->bind_param("ss", $name, $surname);

// Execute the statement
$stmt->execute();

// Get the result set
$result = $stmt->get_result();
```

3. Move the functions `doesItExist()` and `countPeople()` outside of the `if` statement for better organization.

4. Modify the way you display the results. Instead of echoing directly inside the loop, you can store them in an array first, and then display them outside the loop. Here's an example:

```php
// Create an array to store the results
$results = array();

while ($row = $result->fetch_assoc()) {
    $arr = doesItExist($row);
    $results[] = $arr;
}

// Display the results
foreach ($results as $result) {
    echo "Name: " . $result['name'] . "<br>";
    echo "Last name: " . $result['surname'] . "<br>";
    echo "Feedback: " . $result['feedback'] . "<br>";
}
```

By making these changes, you should be able to fix the issues with your code and make it work as intended. Remember to also handle any potential errors that may occur during database operations.
  •  


If you like DNray forum, you can support it by - BTC: bc1qppjcl3c2cyjazy6lepmrv3fh6ke9mxs7zpfky0 , TRC20 and more...