sql >> Databasteknik >  >> RDS >> Mysql

infoga data i mysql-databasen med php

EDIT:ett enkelt exempel

gör <form> , validering och infogning i ett fil, säg 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> av samma sida...

<? // 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 användningen av en ternary-operator för att ställa in value -attribut för <input> -element:

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


  1. Hur synkroniserar jag Visual Foxpro dbfs med MySQL?

  2. Formatera nummer till förkortat nummer

  3. Python MySQLdb platshållare syntax

  4. MacOS Kan inte starta MySQL Server