【问题标题】:Trying to insert/update two different tables with multiple values尝试插入/更新具有多个值的两个不同表
【发布时间】:2014-06-11 02:25:50
【问题描述】:

我正在尝试使用 PHP 代码更新 mySQL 数据库中的两个不同表。一个块完美运行,但从“if(isset ...”我收到“查询数据库时出错”消息,所以很明显我试图添加数组值(复选框)的代码不起作用。我不是什么看到了吗?

EDIT.PHP

   <h3>Edit Profile: <?php echo $_REQUEST['first_name'];?></h3>
   <form enctype="multipart/form-data" method="POST" action="change.php"> 
   <table border="0" width="60%">

   <tr><td width="30%">First Name: </td><td><input type="text"
   name="upd_first_name" value="<?php echo $_REQUEST['first_name'];?>" maxlength="20"> </td></tr>

   <tr><td width="30%">Last Name: </td><td><input type="text"
   name="upd_last_name" value="<?php echo $_REQUEST['last_name'];?>" maxlength="20"> </td></tr>

   <tr><td width="30%">Email: </td><td><input type="text"
   name="upd_email" value="<?php echo $_REQUEST['email'];?>" maxlength="45"> </td></tr>

   <tr><td width="30%">Password: </td><td><input type="password"
   name="upd_password" id="upd_password" value="<?php echo $_REQUEST['password'];?>" maxlength="20"> </td></tr>

   <tr><td width="30%">Confirm Password: </td><td><input type="password"
   name="upd_cpassword" id="upd_cpassword" value="<?php echo $_REQUEST['password'];?>" maxlength="20" onkeyup="checkPass(); return false;"> </td></tr>

   <tr><td width="30%">Profile Visbility: </td><td><input type="radio"    name="upd_profilevis" value="1" id="1" checked> Private <input type="radio"   name="upd_profilevis" value="2" id="2" > Public </td></tr>

  <<tr><td width="30%">Industries: </td><td>
  <input type="checkbox" name="industries[]" value="1"/>None</br>
  <input type="checkbox" name="industries[]" value="2"/>Film</br>
  <input type="checkbox" name="industries[]" value="3"/>Television</br>
  <input type="checkbox" name="industries[]" value="4"/>Music</br>
  <input type="checkbox" name="industries[]" value="5"/>Gaming</br>
  <input type="checkbox" name="industries[]" value="6"/>Books</br>
  <input type="checkbox" name="industries[]" value="7"/>Comic Books</br>
  </td></tr>

  <tr><td width="30%">Link: </td><td><input type="text"
  name="upd_link" value="<?php echo $_REQUEST['profile_link'];?>" maxlength="45"> </td></tr>

  <tr><td width="30%">Bio: </td><td><input type="text"
  name="upd_bio" value="<?php echo $_REQUEST['bio'];?>" maxlength="500"> </td></tr>

  <input type="hidden" name="MAX_FILE_SIZE" value="10000000">
  <tr><td width="30%">Picture: </td><td><input type="file" id="image" name="image"></tr>
  </table>
  <span id="confirmMessage" class="confirmMessage"></span><br /> 

  <input type="submit" value="Save & Update"/>
  <input type="hidden" name="id" value="<?php echo $_REQUEST['id'];?>">
  </form>

CHANGE.PHP(我得到错误的地方)

<?php
//pulls data/files from the edit.php form
$id= $_REQUEST['id'];
$upd_first_name= $_REQUEST['upd_first_name'];
$upd_last_name= $_REQUEST['upd_last_name'];
$upd_email= $_REQUEST['upd_email'];
$upd_password= $_REQUEST['upd_password'];
$upd_cpassword= $_REQUEST['upd_cpassword'];
$upd_profilevis= $_REQUEST['upd_profilevis'];
$upd_link= $_REQUEST['upd_link'];
$upd_bio= $_REQUEST['upd_bio'];
$mypic = $_FILES['image']['name'];
$temp = $_FILES['image']['tmp_name'];
$type = $_FILES['image']['type'];


//checks if the picture is of the right type before inserting
if(($type=="image/jpeg") || ($type=="image/jpg") || ($type=="image/png") || ($type=="image/bmp") || ($type=="image/gif")) {

    //connects to the database
    $dbc = mysqli_connect('localhost', 'root', 'root', 'profile') or die('Error connecting to MySQL server.');

    //if industries are selected on the form edit.php insert into table 
    //each industry assigned to the member ID (junction table)
        if(isset($_POST['industries'])) {

            //deletes from table current values
            $query = "DELETE FROM `industry_has_member` WHERE member_idmember='$id'";
            $result = mysqli_query($dbc, $query) or die(mysqli_error($dbc));
            //to report errors
            if(!$result)
                {
                printf("Errormessage: %s\n", mysqli_error($dbc));
                }
            //adds on table new values
            foreach ($_POST['industries'] as $industry) {
            $query = "INSERT INTO industry_has_member (industry_idindustry, member_idmember) values ('$industry', '$id')";
            $result = mysqli_query($dbc, $query) or die(mysqli_error($dbc));
            //to report errors
            if(!$result)
                {
                printf("Errormessage: %s\n", mysqli_error($dbc));
                }
            }
        }

    $query = "UPDATE `member` SET member_stamp=now(), first_name='$upd_first_name', last_name='$upd_last_name', email='$upd_email', password='$upd_password',       profile_vis_idprofile_vis='$upd_profilevis', profile_link='$upd_link', prof_image='$mypic', bio='$upd_bio' WHERE idmember='$id'";

    //displays the results into a table
    $result = mysqli_query($dbc, $query) or die('Error querying database.');

    move_uploaded_file($temp,"images/$mypic");

    echo "<h2>Your profile has been updated</h2><br /><h3>Here is your profile picture</h3>";
    echo "<img border='1' width='200' height='200' src='images/$mypic'>";

    mysqli_close($dbc);

    } 
?>

【问题讨论】:

  • 你能把die('Error querying database')替换成die(mysqli_error($dbc))来显示mysql错误信息吗?
  • 因此,我将两个 die 语句替换为您建议的语句,并且它有效……但仅适用于新条目。如果我已经有数据库中的数据,当它不起作用并显示这个...重复条目'2-6'键'PRIMARY'所以我的问题是用新的更新更新现有条目......你会怎么做建议我添加到代码中以确保这两种情况都有效?
  • 您的代码中还有两个问题:SQL 注入(在 "...VALUES ('$industries', '$id')...")和跨站点脚本(在 ' ...value="link 和 link
  • 请看看我在下面最后一篇文章中的 cmets,让我知道你的想法。
  • 我认为这篇文章回答了我的问题:stackoverflow.com/questions/19540781/…

标签: php mysql foreach isset multiple-tables


【解决方案1】:

您需要将所有操作包装在一个事务中。

if (isset($_POST['industries'])) {
    $industry_ids = $_POST['industries'];
    $id = $_POST['id'];

    try {
        $dbc->begin_transaction();
        $dbc->query("delete from industry_has_member where member_idmember=$id") or throw new Exception($dbc->error);

        foreach ($industry_ids as $industry_id) {
            $dbc->query("insert ignore into industry_has_member (industry_idindustry, member_idmember) values ($industry_id, $id)" or throw new Exception($dbc->error);
        }
        $dbc->commit();
    } catch (Exception $e) {
        echo $e->getMessage();
        $dbc->rollback();
    }
}

【讨论】:

  • 请看看我在下面最后一篇文章中的 cmets,让我知道你的想法。
  • @EmmanuelHenri,是的,现在说得通了。我已经相应地更新了答案
  • 我假设这个函数在 if(isset) 和 foreach() 函数下?
  • 谢谢。您能快速查看我上面更新的代码(change.php)并告诉我这是否正确吗?
  • @EmmanuelHenri,对不起,我误解了你的数据结构。查看更新的答案
【解决方案2】:

尝试用

扩展你的插入问题
on duplicate key update

见:Insert into a MySQL table or update if exists

【讨论】:

  • 如果你想覆盖,使用上面的。如果您不想覆盖,请使用 user3678068 的答案。
  • 我真正想要的是更新。例如,如果用户在 mysql 数据库中已经有行业 2-3-4,并且当用户使用他选择 1-4-6 的表单更新它时,我只希望 1-4-6 显示在数据库中用户。现在,使用 REPLACE INTO 或 UPDATE ON DUPLICATE 语句,数据库将使用此用户 ID 显示 1-2-3-4-6。我想我需要以不同的方式处理这个问题。当项目被选中和未选中时,我需要创建一个不同的名称,因此我创建了删除未选中项目并添加已选中项目的逻辑。大家觉得呢?
  • 在查看了我的代码和逻辑之后,我终于找到了我的逻辑和代码的答案并对其进行了更新(change.php),它可以工作了!!!谢谢大家的帮助,它帮助我弄清楚了。
猜你喜欢
  • 1970-01-01
  • 2014-02-04
  • 2020-03-11
  • 2019-05-05
  • 1970-01-01
  • 2015-03-14
  • 2016-12-29
  • 1970-01-01
  • 2018-01-24
相关资源
最近更新 更多