简体   繁体   中英

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) VALUES($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)");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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