Mysql
 sql >> Teknologi Basis Data >  >> RDS >> Mysql

memasukkan data ke database mysql menggunakan php

EDIT:contoh sederhana

lakukan <form> , validasi dan penyisipan di satu file, katakan form.php :

<? // check if FORM has been posted

$posted = isset($_POST['submit']);

 if ($posted) { // form has been posted...

    // validate input

    if (!isset($_POST['item']) || strlen(trim($_POST['item'])) == 0)
        $error['item'] = "please insert an item-name!";

    if (!isset($_POST['price']) || !is_numeric($_POST['price']))
        $error['price'] = "please enter a valid price!";


    // ready for input?

    if (!isset($error)) { // no $error --> go insert!

        // I'll do the db-operation with PDO and a prepared statement.
        // this is cool, easy and safe. LEARN IT!

        $sql = "INSERT INTO table (item,price) VALUES (:item,:price)";

        $insert = $db->prepare($sql);
        $insert->execute(array(
            ':item' => $_POST['item'], 
            ':price' => $_POST['price']
            ));
    } // $error
 } // submit
?>

Sekarang, di <body> dari sama halaman...

<? // check whether to display confirmation or form...

if ($posted && !isset($error)) { 

    // form was sent AND no error --> confirm
?>
<h1>Confirmed!</h1>
<p>Your data has been sent, thank you very much!</p>
<a href="somepage.php">go to somepage</a>
<?

} else {

    // form not sent or errors --> display form
?>

<h1>Please enter data</h1>

<? // display error-message, if there's one:
if (isset($error)) {
    $output = "";
    foreach ($error as $field => $msg) 
        $output .= (strlen($output) > 0?', ':'') . "[$field]: $msg";
    echo "<p>There were errors: $output</p>";
} // $error
?>

<form method="post">
    <!-- if the form has been sent, bring back the field's value from $_POST -->
    <p>item-name: <input type="text" name="item" 
        value="<?=($posted?$_POST['item']:'')?>" /></p>
    <p>price: <input type="text" name="price" 
        value="<?=($posted?$_POST['price']:'')?>" /></p>
    <p><input type="submit" name="submit" value="submit" /></p>
</form>

<?
} // submit & $error
?>

Lihat penggunaan ternary-operator untuk menyetel value -atribut <input> -elemen:

(<condition>?<what to do if true>:<what to do if false>)


  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Otomatiskan Penerapan MySQL atau Cluster Postgres Anda Dari Cadangan

  2. Membatasi kolom untuk menerima hanya 2 nilai

  3. Perbarui kueri gagal dengan kesalahan:1175

  4. Bagaimana menemukan semua hubungan antara semua tabel mysql?

  5. Bagaimana cara mengekspor database MySQL ke JSON?