0

I am new to PHP and I am trying to enter details into my database.

Session I want to insert data into database with

<form method="post" action="">
  <input name="p_date" type="date">
  <input name="r_date" type="date">
</form>

 if (!empty($_POST)) {
     $_SESSION['p_date'] = $_POST['p_date'];
     $_SESSION['r_date'] = $_POST['r_date'];
}

This code, Url on the side True is spinning but can't add data to database. Where could i be wrong?

if(isset($_POST['dateSearch'])) {
    $insert=$connect->prepare("Insert Into test (p_date,r_date) VALUES ('{$_SESSION['p_date']}','{$_SESSION['r_date']}'");

    if($insert) {
        header("Location:cars.php?Status=True");
    }
    else {
        header("Location:cars.php?Status=False");

    }
}

Thanks in advance..

JustFeel
  • 23
  • 5
  • 5
    You're never executing the query, just preparing it. – Barmar Jun 30 '21 at 15:40
  • 3
    You also shouldn't substitute variables directly into the query. Put placeholders in the query, then use `bind_param()` to associate variables withthe placeholders. – Barmar Jun 30 '21 at 15:41
  • Or `bindParam()` if you're using PDO. – Barmar Jun 30 '21 at 15:56
  • Could you write it as code? Because PHP in the field i'm a new :\ – JustFeel Jun 30 '21 at 15:59
  • See https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php and many other resources, it already contains enough examples for you to work from – ADyson Jun 30 '21 at 16:01
  • Btw it's unclear how the two pieces of code you've posted actually link together. What is the flow? There's a form, you submit it and set some session values, that's clear enough... but then what? How does the second script come into it? Your post lacks context. – ADyson Jun 30 '21 at 16:02

1 Answers1

1

for pdo this is how it should be done:

$sql = "INSERT INTO test (p_date,r_date) VALUES (?,?)";
$stmt= $pdo->prepare($sql);
$stmt->execute([$p_date,$r_date]);

for mysqli you can do like this:

    $stmt = $conn->prepare("INSERT INTO test (p_date,r_date) VALUES (?, ?)");
    $stmt->bind_param("ss", $p_date,$r_date);
    
    $p_date = 'string';
    $r_date ='string';
    $stmt->execute();
    $stmt->close();
Syed Umair
  • 86
  • 1
  • 5
  • I think it would be better to show named placeholders in the PDO example. That's one of the major benefits of PDO. – Barmar Jun 30 '21 at 16:17