简体   繁体   English

使用PHP在MySql数据库中插入,更新,搜索

[英]Insert, Update, Search in MySql database using PHP

This is my first post in this forum, despite being a devoted follower for years now. 尽管多年来一直是我的忠实拥护者,但这是我在该论坛上的第一篇文章。

I have built a simple system that registers lot numbers and their locations within a MySQL database through a PHP form. 我建立了一个简单的系统,该系统通过PHP表单在MySQL数据库中注册批号及其位置。

Then i have this other form called "Errata Corrige" that I use to find and edit eventual mistaken entries. 然后,我使用了另一种称为“勘误表”的表格,用于查找和编辑最终的错误条目。

It's search criteria is an (UNSIGNED INT UNIQUE) value named "lotto" and everything works (worked) like a charm under this circumstances. 它的搜索条件是一个名为“ lotto”的(UNSIGNED INT UNIQUE)值,在这种情况下,一切都像魅力一样起作用(起作用)。

Now the thing got a little tricky. 现在,事情变得有些棘手了。

I found out that lot numbers (lotto) for work purposes are not always unique values, there might be more than one entry with the same number. 我发现用于工作目的的批号(lotto)并不总是唯一的值,可能有多个具有相同编号的条目。

No problem making the "Insert" form or various counters work under this new circumstances, but it got really tricky within the EDIT functions. 在这种新情况下,使“插入”表格或各种计数器正常工作是没有问题的,但是在EDIT函数中确实很棘手。

This is my PHP code: ` 这是我的PHP代码:

<?php

$id = "";
$settore = "";
$ubicazione = "";
$numero = "";
$lotto="";

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

// connect to mysql database
try{
    $connect = mysqli_connect($host, $user, $password, $database);
} catch (mysqli_sql_exception $ex) {
    echo 'Error';
}

// get values from the form
function getPosts()
{
    $posts = array();
    $posts[0] = $_POST['id'];
    $posts[1] = $_POST['settore'];
    $posts[2] = $_POST['ubicazione'];
    $posts[3] = $_POST['numero'];
    $posts[4] = $_POST['lotto'];

    return $posts;
}

// Search

if(isset($_POST['search']))
{
    $data = getPosts();

    $search_Query = "SELECT * FROM mappa WHERE lotto = $data[4]";

    $search_Result = mysqli_query($connect, $search_Query);

    if($search_Result)
    {
        if(mysqli_num_rows($search_Result))
        {
            while($row = mysqli_fetch_array($search_Result))
            {
                $id = $row['id'];
                $settore = $row['settore'];
                $ubicazione = $row['ubicazione'];
                $numero = $row['numero'];
                $lotto = $row ['lotto'];
            }
        }else{
            echo 'Lotto non presente in archivio';
        }
    }else{
        echo 'Error';
    }
}


// Insert
if(isset($_POST['insert']))
{
    $data = getPosts();
    $insert_Query = "INSERT INTO `mappa`(`settore`, `ubicazione`, `numero`, `lotto` ) VALUES ('$data[1]','$data[2]',$data[3], $data[4])";
    try{
        $insert_Result = mysqli_query($connect, $insert_Query);

        if($insert_Result)
        {
            if(mysqli_affected_rows($connect) > 0)
            {
                $resInsert = "1 nuovo dato inserito correttamente!";
            }else{
                $resInsert = "Nessun dato inserito";
            }
        }
    } catch (Exception $ex) {
        echo 'Errore '.$ex->getMessage();
    }
}


// Edit
if(isset($_POST['update']))
{
    $data = getPosts();
    $update_Query = "UPDATE `mappa` SET `settore`='$data[1]',`ubicazione`='$data[2]',`numero`=$data[3],`lotto`=$data[4] WHERE `id` = $data[0]";
    try{
        $update_Result = mysqli_query($connect, $update_Query);

        if($update_Result)
        {
            if(mysqli_affected_rows($connect) > 0)
            {
                $resAgg = "1 dato aggiornato correttamente!";
            }else{
                $resAgg = "Nessun dato aggiornato!";
            }
        }
    } catch (Exception $ex) {
        echo 'Error Update '.$ex->getMessage();
    }
} ?>

` `

HTML: HTML:

 <form action="mod.php" method="post" class="form-horizontal form-bordered" style="text-align:center">

    <div class="form-group has-error" style="padding-top:30px">
    <label class="col-xs-3 control-label" for="state-normal">ID</label>
    <div class="col-lg-3">
    <input type="text" name="id" placeholder="ID" class="form-control" value="<?php echo $id;?>">                                            </div>
    </div>

    <div class="form-group">
    <label class="col-md-3 control-label" for="state-normal">Settore</label>
    <div class="col-md-6">
    <input type="text" name="settore" placeholder="Settore" class="form-control" value="<?php echo $settore;?>">                                            </div>
    </div>

    <div class="form-group">
    <label class="col-md-3 control-label" for="state-normal">Ubicazione</label>
    <div class="col-md-6">
    <input type="text" name="ubicazione" placeholder="Ubicazione" class="form-control" value="<?php echo $ubicazione;?>">                                            </div>
    </div>

    <div class="form-group">
    <label class="col-md-3 control-label" for="state-normal">Numero</label>
    <div class="col-md-6">
    <input type="text" name="numero" placeholder="Numero" class="form-control" value="<?php echo $numero;?>">                                            </div>
    </div>

    <div class="form-group has-success">
    <label class="col-md-3 control-label" for="state-normal">Lotto</label>
    <div class="col-md-6">
    <input type="text" name="lotto" placeholder="Lotto" class="form-control" value="<?php echo $lotto;?>">                                            </div>
    </div>

        <div style="padding-top:16px">
            <!-- Insert-->
            <button type="submit" name="insert" value="Add" class="btn btn-effect-ripple btn-primary">Inserisci</button>
            <!-- Update-->
            <button type="submit" name="update" value="Update" class="btn btn-effect-ripple btn-info">Aggiorna</button>
            <a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</a>
            <!-- Search-->
            <button type="submit" name="search" value="Find" class="btn btn-effect-ripple btn-success">Cerca</button>
        </div>
    </form>

While the lot number was unique everything worked like a charm. 尽管批号是唯一的,但所有内容都像一个饰物。

Now that there are multiple data with the same lot number the code became obsolete since the "search" function only shows the last (greatest ID) data. 现在,存在具有相同批号的多个数据,由于“搜索”功能仅显示最后(最大ID)数据,因此代码已过时。

I have tried to work around a loop and tell the function to search every ID where lotto = lotto but it didn't work. 我试图绕过一个循环,并告诉该函数在lotto = lotto的位置搜索每个ID,但没有用。

A simple solution would be obviously searching through ID instead of lotto but that is a pretty crapy one, since the user only knows (and is interested in) Lot Numbers not the ID it was assigned during data insertion. 一个简单的解决方案显然是通过ID而不是乐透进行搜索,但这是一个非常坎的解决方案,因为用户只知道(感兴趣)批号,而不是在数据插入期间分配的ID。

Then I tried to put two php functions into one page, the first that fetches data from Mysql into a PHP dropdown menu, telling it to show every ID that matches the search criteria (lotto): 然后,我尝试将两个php函数放到一个页面中,第一个将从Mysql中获取数据的页面放到一个PHP下拉菜单中,告诉它显示与搜索条件(lotto)匹配的每个ID:

 <?php if (isset($_POST['submitted'])){

                  include ('../mysql_connect.php');   // connessione al database

                  $category = 'lotto';
                  $criteria = $_POST['criteria'];
                  $query = "SELECT * FROM mappa WHERE $category = '$criteria'";
                  $result = mysqli_query($dbcon, $query) or die('Impossibile reperire i dati');


                  while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){

                            $idTab = $row['id'];
                             echo "<option>
                             $idTab </option>";


            }

              } // FINE if ?>
            </select>

Fetching data from MySQL into the dropdown worked just fine, but I got stucked in the syntax trying to use this dropdown as a search criteria for my first function. 从MySQL提取数据到下拉列表工作正常,但是我陷入了试图将下拉列表用作第一个函数的搜索条件的语法中。

Every help would really be appreciated! 每一个帮助将不胜感激! Thank you in advance for your answers. 预先感谢您的回答。

You said that lotto is unique. 您说乐透是独一无二的。 So how come you are able to insert multiple rows with the same lotto? 那么,您怎么能用相同的乐透插入多行呢? Remove the unique constraint from the lotto column. 从Lotto列中删除唯一约束。

Try the following: 请尝试以下操作:

$query = select lotto, group_concat(id) as ID numbers from mappa where lotto = 'user search number' group by lotto;
$result = $conn->query($query);
$rows = $result->num_rows;

$result->data_seek(0); //move to first row (which is the only one)
$row = $result->fetch_array(MYSQLI_NUM); //fetch array

$id_numbers_string = $row[1]; //store the values of the row's second column (which is number 1)
$id_numbers_separated_array = explode(",", $id_numbers_string); //create an array with the values in the string
    for($i = 0; $i < count($id_numbers_separated_array); $i++){ //loop through created array
        echo "ID: " . $id_numbers_separated_array[$i];
        echo "<br>";
    }

Also try to run the query in your database management system to see the results. 另外,尝试在数据库管理系统中运行查询以查看结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM