Hi!
I have a form, where you can choose between 5 titles of books. Under it you have a submit button.
My question is:
how to make so, that when the customer has chosen a book and clicks on the submit button, the title of the book to be inserted(recorded) in a db table.
I suppose it should be smth connected with if clause and INSERT INTO , but i'm not sure for the syntax.
Thank you, very, very much for the help!!!

Dani AI

Generated

Summary of what's missing in the thread and a safe, modern pattern to follow. @evelkova asked how to save the selected book title; and correctly pointed to handling the submit and storing the selection. For production code use parameterized queries (PDO or mysqli), validate the value against a known list of five titles, and never rely on the old `mysql*` extension (removed in modern PHP).

A minimal, practical flow:

  • keep the five book titles server-side (whitelist) so only valid titles are accepted;
  • read the POST field and check it against the whitelist;
  • use a prepared INSERT to avoid SQL injection and set the connection charset to utf8mb4.

Example (adapt to your DB/column names):

<?php
$allowed = ['Title A','Title B','Title C','Title D','Title E'];
$book = $_POST['book'] ?? '';

if (!in_array($book, $allowed, true)) {
    http_response_code(400);
    exit('Invalid selection');
}

$pdo = new PDO('mysql:host=localhost;dbname=shop;charset=utf8mb4', 'dbuser', 'dbpass', [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);

$stmt = $pdo->prepare('INSERT INTO orders (book_title, created_at) VALUES (:title, NOW())');
$stmt->execute([':title' => $book]);
?>

Troubleshooting and hardening notes: enable PDO exceptions for clearer error messages during development, log server-side errors rather than echoing them, ensure DB user has INSERT rights, and add a CSRF token for form submits. When showing the saved title back in HTML, escape with htmlspecialchars. For details on prepared statements see the PHP manual on PDO prepared statements. For broader input-handling guidance and SQL injection prevention see the OWASP SQL Injection Prevention Cheat Sheet.

Recommended Answers

All 4 Replies

Use this code:
this code will execute after user clicks on the submit button.

if($_SERVER['REQUEST_METHOD']=='POST')
{
mysql_query("insert query");
}

Many thanks :)

Hi,

Shanti is very much right. You should just rephrase it. Declare a separate variable.

$selection = $_REQUEST['select'];
if($selection != null)
... Insert into database;

That's it! You might want to add some security here and validate $selection.

All the best!
References:-http://www.tutorialindia.com/php_mysql/index.php

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.