检查MySQL数据库中是否存在字符串

时间:2013-10-16 09:25:45

标签: php mysql

查看帖子并使用Google后,我认为我已经掌握了答案的基本组成部分,但由于缺乏MySQL经验,我不能完全确定如何将它们组合在一起。

---编辑开始(2013/10/16 @ 1110GMT --- 以下是代码目前的外观:

    $username="username"; $password="password"; $database="database";
    mysql_connect(localhost,$username,$password);@mysql_select_db($database) or die(
    "Unable to select database");

    $needle = 'sdfsdf';

    $checkUserID = mysql_query("SELECT * FROM order_option WHERE value LIKE '%$needle%' ");
    if (!$checkUserID) {
        die('Query failed to execute for some reason');
    }

    if (mysql_num_rows($checkUserId) > 0) {
        echo "<p>User id exists already.</p>";
        $user = mysql_fetch_array($checkUserId);
        print_r($user); // the data returned from the query
    }
    mysql_close();

我想知道我是否可能误解了MySQL,虽然我知道应该从这个MySQL中提取查询         TRUNCATE TABLE order_option;

    INSERT INTO `order_option` (`order_option_id`, `order_id`, `order_product_id`, `product_option_id`, `product_option_value_id`, `name`, `value`, `type`) VALUES ('13', '2', '2', '237', '0', 'Additional Information', 'sdfsdf', 'textarea');
    INSERT INTO `order_option` (`order_option_id`, `order_id`, `order_product_id`, `product_option_id`, `product_option_value_id`, `name`, `value`, `type`) VALUES ('14', '2', '2', '228', '0', 'Website', 'fsdfsd', 'text');

---编辑结束---

脚本如下:

$user="user"; $password="password"; $database="mydatabase";
mysql_connect(localhost,$user,$password);
@mysql_select_db($database) or die("Unable to select database");

$needle = 'sdfsdf';

$checkUserID = mysql_query("SELECT value from order_option WHERE value = '$needle'");
if (!$checkUserID) {
    die('Query failed to execute for some reason');
}

if (mysql_num_rows($checkUserId) > 0) {
    echo "User id exists already.";
    $user = mysql_fetch_array($checkUserId);
    print_r($user); // the data returned from the query
}

mysql_close();

如果上面的代码是正确的,我需要知道如何使用它

if ($result == $needle) {
    echo('found'); 
} else { 
    echo('not found'); 
}

1 个答案:

答案 0 :(得分:0)

您的代码已经测试了要找到的$ needle

if (mysql_num_rows($checkUserId) > 0) {

此小行查找与您的查询匹配的结果数。如果有超过0(另一个词:如果找到匹配!)它继续。

符合您的要求:

if (mysql_num_rows($checkUserId) > 0) 
  {
  echo "found";
  {
else
  {
  echo "not found";
  }