在MYSQL表中搜索条目

时间:2014-07-27 05:00:27

标签: php

我有一个名为members的MYSQL表,其中包含2列,如下所示:

username
john
sam

colleges_i_like
"yale ", "stanford", "columbia"
"princeton", "cornell"

我想创建一个PHP查询,允许我选择喜欢某个大学($ college)的用户。

我写了这段代码,但它不起作用(我是PHP的新手,这是我写的第一行代码)。你能帮我纠正一下吗?

$college='yale';
$result = "SELECT * FROM members where $college IN 'colleges_i_like'";

3 个答案:

答案 0 :(得分:1)

首先,请确保至少使用PHP MySQLi而不是弃用MySQL扩展名。

其次,如果你想将某些东西与其他东西匹配,你应该使用WHERE语句。下面是我为MySQLi编写的代码。

使用MySQLi时的连接:

$myDB = new mysqli("localhost", "username", "password", "dbname");

你必须写下这样的东西:

// Prepare you QUERY to be exeuted, note the questuion mark at the end of
//  of the query, this should be replaced with a real value 
$stmt = $myDB->prepare("SELECT * FROM myTable WHERE colleges_i_like = ?");

// In this statement we replace the ? with real variable. "s" means string and
// I assume your colleges_i_like is string.
$stmt->bind_params("s", $myCollege);

// execute your query
$stmt->execute();

// get the result (PHP 5.4 > )
$result = $stmt->get_result();

// iterating over the results
while($row = $result->fetch_array(MYSQL_ASSOC))
{
   echo "Username is: " . $row["username"] . "<br />";
}

现在,如果您所在领域有多所大学,则查询应如下:

$stmt = $myDB->prepare("SELECT id, username FROM myTable WHERE colleges_i_like LIKE ?");

然后用你的变量(在bind_param()中替换?)包装:

$colleges = "%"."CollegeName"."%";

我想补充一点,如果你的PHP版本低于5.4,为了获取结果,你应该遵循这个:

$results = array();

// Instead of star, we use certain fields so that our job in fetching them gets easier
$stmt = $myDB->prepare("SELECT id, username FROM myTable WHERE colleges_i_like = ?");

// bind params (no change)
$stmt->bind_params("s", $myCollege);

// execute your query (no change)
$stmt->execute();

// we binds the results to certain variables. Define the variable first, so to avoid
// undefined warning/notice
$stmt->bind_result($results['id'], $results['username']);

// fetching the results
while($stmt->fetch())
{
   echo "Id is: " . $row["id"] . "<br />";
   echo "Username is: " . $row["username"] . "<br />";
}

答案 1 :(得分:1)

尝试类似:

$college='yale';
$result = "SELECT * FROM members where 'colleges_i_like' LIKE '%".$college."%'";

答案 2 :(得分:1)

如果两列在同一个表中且数据在&#34; college_i_like&#34;在单独的行中你可以这样做:

$query = "SELECT * FROM members WHERE college_i_like LIKE '%yale%'";
$result = mysql_query($query);
if(!$result){
    die(mysql_error());
}