简体   繁体   English

将mysql表从单个输入更新为不同的列

[英]Update mysql table from a single input to different columns

I have a table called dircode : 我有一个名为dircode的表:

CREATE TABLE dircode (
  jobcodeid int(11) NOT NULL AUTO_INCREMENT,
  jobcodeserial varchar(255) NOT NULL,
  jobcode1 varchar(255) NOT NULL,
  codestatus1 varchar(60) NOT NULL,
  jobcode2 varchar(255) NOT NULL,
  codestatus2 varchar(60) NOT NULL,
  jobcode3 varchar(255) NOT NULL,
  codestatus3 varchar(60) NOT NULL,
  jobcode4 varchar(255) NOT NULL,
  codestatus4 varchar(60) NOT NULL,
  PRIMARY KEY (jobcodeid)
)

A user may have upto 4 job codes for single serial number. 一个序列号最多可以有4个作业代码。 When a user inputs a dir serial number and one code, I want that particular job's codestatus to be updated to 'Used' . 当用户输入目录序号和一个代码时,我希望将该特定作业的codestatus更新为'Used' The rest of the data should remain intact. 其余数据应保持不变。 For example, when a user enters a serial number and jobcode3 the status of codestatus3 should get updated to 'Used' . 例如,当用户输入一个序列号和jobcode3的状态codestatus3应该得到更新,以'Used' Please help me in writing PHP code for the above query. 请帮我编写上述查询的PHP代码。

As you said, you need to UPDATE the row. 如您所说,您需要更新该行。

You are trying to first find out if the entered code is 1, 2, 3 or 4 (eg jobcode3 ) and then set the status of that code (in this case codestatus3 ). 您试图首先找出输入的代码是1、2、3还是4(例如jobcode3 ),然后设置该代码的状态(在本例中为codestatus3 )。 To do that, I would (or wouldn't, see below) get the whole row as an associative array and figure the index out in your code (check each jobcode, find the code and extract the index from the column name). 为此,我将(或不会,如下所示)将整个行作为一个关联数组,并在代码中找出索引(检查每个作业代码,找到代码并从列名中提取索引)。

Then connect to the MySQL server and execute a query like this: 然后连接到MySQL服务器并执行如下查询

$columName = "codestatus" . $theCorrectIndex;
mysql_query(sprintf("UPDATE dircode SET %s = 'Used' WHERE jobcodeid = %d",
                      $columName,$dircodeId));

Check the boolean return. 检查布尔值返回。 If it's false , examine the details on the error . 如果为false ,请检查有关错误详细信息

(Alternatively, you could put all this inside your SQL query, see this question or this and MySQL's control flow functions .) (或者,你可以把这个所有的SQL查询中,看到这个问题,或者这个和MySQL的控制流的功能 。)

This is not a very good solution. 这不是一个很好的解决方案。 You might want to think about creating another table codes with columns id , status and foreign key column dircode_id so you avoid putting indices into your column names (usually not a good idea). 您可能需要考虑使用列idstatus和外键列dircode_id创建另一个表codes ,以便避免在列名中添加索引(通常不是一个好主意)。

Also, there is a lot of documentation on this around ( MySQL , PHP , SO ). 另外,关于这方面有很多文档( MySQLPHPSO )。

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

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