[英]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中构建脚本来执行以下操作:
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. 请注意,参数上的文本长度与最长的文本字段一样长。
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.