sql >> Database teknologi >  >> RDS >> Mysql

indsættelse af data i mysql-database ved hjælp af php

EDIT:et simpelt eksempel

gør <form> , validering og indsættelse i one fil, sig 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 ?>

Nu i <body> af samme side...

<? // 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 ?>

Se brugen af ​​en ternary-operator for at indstille value -attribut for <input> -elementer:

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


  1. #1136 - Kolonneantal stemmer ikke overens med værdiantallet i række 1

  2. SQLiteAssetHelper:Kunne ikke åbne databasen til skrivning (prøver skrivebeskyttet)

  3. Få antallet af dage i en måned i PostgreSQL

  4. pandaer - Sammenfletning på strengkolonner virker ikke (fejl?)