使用参数抛出无效参数号的SQL

时间:2015-11-19 17:10:08

标签: php mysql sql

所以我试图在SQL中使用“LIKE”,基本上是为了看一个玩家是否已经在团队中。这是我的代码:

    $checkifonlytwo = "SELECT * FROM sg_turn_teams WHERE joinid = :joinid AND players LIKE '%:ownerid,%'";
    $paramstwo = array(
        ":joinid" => $joinid,
        ":ownerid" => $_SESSION['user']['id']
    );
    try{
    $stmttwo = $db->prepare($checkifonlytwo);
    $resulttwo = $stmttwo->execute($paramstwo);
    }
    catch(PDOException $ex){
        die("Failed to run query #2: " . $ex->getMessage());
    }

另外你可以看到我希望它是LIKE '%1,%'例如,所以最后也是逗号。

我的表格结构如下所示。 table structure

编辑,玩家将会像“1,2,3”一样没有名字,因为用户可以更改他们的名字。图片有名字,但它应该是1,2,3

1 个答案:

答案 0 :(得分:5)

前言。我决定将其作为社区维基。我不想从中获得任何东西,除了OP和其他人访问这个问题。

正如我在评论中所说的那样,你用ownerid,中的逗号来解决错误的方法。

您需要做的是在阵列上implode并使用IN()

借鉴https://stackoverflow.com/a/12151295/

$e = 0;

while($e<$num1){
$units = 0;
$r = 0;
$SO_Line_Item=mysql_result($result1,$e,"SO_Line_Item");

    foreach ($Boxes[$e] as $a => $b)  
    {

        $zzz[] = $Boxes[$e][$r];

$ce = count($Boxes[$e]);        

    $r++; 
    }
//end inner foreach

$products = implode(',', array_fill(0,$ce, '?'));

$db = new PDO('mysql:host=192.168.1.197 ;dbname=Tracking', $dbuser,$dbpass);
$stmt = $db->prepare("SELECT Box_Num,Timestamp,E3_SN,Assy_Status FROM Current_Box WHERE Box_Num IN( $products )");
$stmt->execute($zzz);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
unset($zzz);
$e++;
}

https://stackoverflow.com/a/2814703/

$ids = array(2, 4, 6, 8);

// prepare a string that contains ":id_0,..,:id_n" and include it in the SQL
$plist = ':id_'.implode(',:id_', array_keys($ids));
$sql   = "SELECT * FROM someTable WHERE someId IN ($plist)";
// prepare & execute the actual statement
$parms = array_combine(explode(",", $plist), $ids);
$stmt  = $PDO->prepare($sql);
$rows  = $stmt->execute($parms);

来自评论:

  

“您可能希望使用关联表,而不是按照存储方式存储信息.-- Maximus2012”

正如评论中所提到的,来自SO的一些问题/答案证明了关联表的概念以及复合主键:

Mysql : Association table

How to use an MySQL association table to return categories not currently assigned to an entry

如果OP决定使用此结构,则需要更改查询以使用LEFT JOIN和/或使用带有IN子句的子查询。 SO上有很多例子。我可以通过简单的搜索找到一个(请忽略慢查询部分并查看示例以演示该概念):

MySQL - SELECT WHERE field IN (subquery) - Extremely slow why?