开发者

mysql if word match statement

how do i save the data, if

1) the word match Pros, it will be saved to t_pros column

2) the word that not match Pros, it will be saved to t_others column

i heard i can use mysql CASE statement, but dont know how to use it?

table pro:
id  t_pros   t_others
------------------------
1   Pros 1x
2   Pros 2x
3            voucher

<input type="text" id="t_pros">
$db->query("INSERT INTO pro(t_pros,t_others) V开发者_StackOverflow中文版ALUES($t_pros, $t_pros)");


So in each row only one of the two columns ever has a value?

In that case, how about:

$column = (preg_match('/^Pros/i', $_POST['t_pros'])) ? 't_pros' : 't_others';
$t_pros = mysql_real_escape_string($_POST['t_pros']);
$db->query("INSERT INTO pro($column) VALUES ($t_pros)");

That is, pick which column based on whether the value begins with 'Pros' or not (just as you indicated), and then just insert into that column, using MySQL's default value (normally NULL) for the other.


First, your input field needs the attribute name="t_pros".

Secondly, this code is open to SQL Injection - read up on it.

The query might look like this:

INSERT INTO pro(t_pros,t_others) VALUES(IF($t_pros = 'Pros', 'Pros', NULL), IF($t_pros = 'Pros', NULL, $t_pros))"

But again, this is not safe. Use mysql_real_escape_string around all variables in your SQL query, or use prepared statements.


if ($t_pros == 'Pros')
  $t_pros_col = $t_pros;
else
  $t_others_col = $t_pros;

$db->query("INSERT INTO pro(t_pros,t_others) VALUES($t_pros_col, $t_others_col)");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜