在表单中使用SELECT和UPDATE查询

时间:2012-02-28 08:21:19

标签: php sql forms prepared-statement

我有一个具有'工厂'主题的数据库。我想要一个脚本来检索玫瑰植物的细节并将值放入字段中。然后,我希望用户能够更新项目并将其提交回数据库。

我希望用户通过拉丁名称从数据库中提取项目,这是'rose'表中的唯一属性。这是插入玫瑰的代码,有人可以帮助我根据我想要的方式调整它,请使用准备好的语句:

//connect to database
$conn2 = DB2();

require_once('header_admin.php');
  /*

if (isset($_POST['addrose'])) 
{

//detect if we have errors or not
$errors = false;
$error_msg = "Error, please try again";

/*
 *  Could do other validation here
 *  Make sure they enter an email address for example
 */

//if we have no errors, do the SQL
if (!$errors) {  

$latin_name = $_POST['latin_name'];
$common_name = $_POST['common_name'];
$variety_name = $_POST['variety_name'];
$colour = $_POST['colour'];
$season = $_POST['season'];
$hardiness = $_POST['hardiness'];
$situation = $_POST['situation'];
$soil_type = $_POST['soil_type'];
$price = $_POST['price'];
$fragrance = $_POST['fragrance'];
$height = $_POST['height'];

//insert data
$stmt = $conn2->prepare("INSERT INTO rosename (latin_name, common_name, variety_name, colour, season_of_interest, hardiness, situation, soil_type, price, 
fragrance, ultimate_height) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

//bind the parameters
  $stmt->bind_param('ssssssssdss', $latin_name, $common_name, $variety_name, $colour, $season, $hardiness, $situation, $soil_type, $price, $fragrance,
  $height);

// Execute query
$stmt->execute();

//if the query worked, put out the confirmation message (you can make this look however you want)
if ($stmt) {
  echo "<p class='black'>Rose Added!</p>";

1 个答案:

答案 0 :(得分:1)

我希望我能得到你想要的东西。 像这样:

if (!$errors) {  

    $latin_name = $_POST['latin_name'];
    $stmt = $conn2->prepare("SELECT * FROM rosename WHERE latin_name = ?"); // replace SELECT * with SELECT field1, field2 (those you need)
    $stmt->bind_param('s', $latin_name);
    if ($result = $stmt->get_result()) {
        /* fetch associative array */
        while ($row = $result->fetch_assoc()) {
            printf ("%s (%s)\n", $row["soil_type"]);
        }
        /* free result set */
        $result->free();
    }
}

来自:http://php.net/manual/de/mysqli-result.fetch-assoc.php

希望有所帮助!