简体   繁体   English

如何修改表中所有行的属性?

[英]How do I modify an attribute across all rows in a table?

My apologies for asking such a novice question but, I need help building a script using either PHP or directly in MySQL that can do the following: 我很抱歉提出这样一个新手问题,但是我需要帮助,可以使用PHP或直接在MySQL中构建脚本来执行以下操作:

  1. Take the values of a column in a table (text) 取得表格中一栏的值(文字)
  2. Change them into capitalized words (from "this is a title" to "This Is A Title") 将它们更改为大写单词(从“这是标题”更改为“这是标题”)
  3. Replace the old values (uncapitalized) with the new values (capitalized). 用新值(大写)替换旧值(大写)。
  1. MySQL doesn't have a function like Oracle's initcap - you have to create the function yourself : MySQL没有像Oracle的initcap这样的函数-您必须自己创建该函数

     DELIMITER $$ DROP FUNCTION IF EXISTS `test`.`initcap`$$ CREATE FUNCTION `initcap`(x char(30)) RETURNS char(30) CHARSET utf8 BEGIN SET @str=''; SET @l_str=''; WHILE x REGEXP ' ' DO SELECT SUBSTRING_INDEX(x, ' ', 1) INTO @l_str; SELECT SUBSTRING(x, LOCATE(' ', x)+1) INTO x; SELECT CONCAT(@str, ' ', CONCAT(UPPER(SUBSTRING(@l_str,1,1)),LOWER(SUBSTRING(@l_str,2)))) INTO @str; END WHILE; RETURN LTRIM(CONCAT(@str, ' ', CONCAT(UPPER(SUBSTRING(x,1,1)),LOWER(SUBSTRING(x,2))))); END$$ DELIMITER ; 

    Mind that the text length on the parameter is as long as your longest text field. 请注意,参数上的文本长度与最长的文本字段一样长。

  2. Use an UPDATE statement : 使用UPDATE语句

     UPDATE TABLE SET text_column = initcap(text_column) 

This is not a function that is native to MySQL, so using PHP's ucwords might save us some time. 这不是MySQL固有的功能,因此使用PHP的ucwords可以为我们节省一些时间。

Note: This will run a single UPDATE query for each row in your table. 注意:这将为表中的每一行运行一个UPDATE查询。

<?php

  $r = mysql_query("SELECT id, name FROM users");
  while($u = mysql_fetch_object($r)){
    $r2 = mysql_query("UPDATE users SET name=".ucwords($u->name)." WHERE id={$u=>id}");
  }

?>

Select your rows with SQL along the lines of: 使用SQL沿着以下行选择行:

SELECT <string> FROM <table> [WHERE <field> = <whatever>]

Update the string using PHP's ucwords() function: 使用PHP的ucwords()函数更新字符串:

$UpperCaseString = ucwords($lowercase);

Update each record: 更新每条记录:

UPDATE <table> SET <fieldname> = <UpperCaseString> WHERE id=<id>

What you'll want to do is fetch all the values, and for each one, run the PHP function ucwords on it. 您要做的就是获取所有值,并为每个值运行PHP函数ucwords Code sample coming shortly... 代码示例即将推出...

EDIT: @smotchkkiss beat me to it -- use his code :-) 编辑:@smotchkkiss击败了我-使用他的代码:-)

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

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