0

I am trying to obtain records from a MYSQL database based on identifiers contained in an array. To get the identifiers my code is as follows:

$query="SELECT agent_id FROM agent_coverage WHERE primary_area LIKE '$search_term%'";
$result=mysqli_query($dbc, $query) or die("Could not obtain primary area coverage2");
while($r=mysqli_fetch_array($result))
{
    $agent_primary[]=$r['agent_id'];
}

This seems to work fine when using print_r to access the array details.

My next statement which is the one that fails is as follows:

if(!empty($agent_primary))
{
    $ids=join(",", $agent_primary);
    $query5="SELECT * FROM detail_db WHERE user_id IN($ids)";
    $result5=mysqli_query($dbc, $query5) or die("Could not do SELECT");

    while($row=mysqli_fetch_array($result5))
    {
    //do stuff with results here.
    }
}

This just fires the die() statement. I have tried using implode instead of join with no success.

edit:
die($dbc->error) after the failing query reveals the error to be: unknown column '' in where clause

20
  • use IN ('1', '2', ...) Commented Feb 7, 2013 at 11:28
  • what does var_dump($query5); output? Commented Feb 7, 2013 at 11:29
  • Where is $dbc defined? Commented Feb 7, 2013 at 11:29
  • '$dbc' is defined at the beginning of the script. This is the db connection details. Commented Feb 7, 2013 at 11:31
  • 1
    I've never heard of "unknown row" error. What is the exact error message? Commented Feb 7, 2013 at 11:40

6 Answers 6

1

Try:

$agent_primary[]="'".$dbc->real_escape_string($r['agent_id'])."'";
Sign up to request clarification or add additional context in comments.

5 Comments

$agent_primary[]="'".$r['agent_id']."'"; seems to work nicely - this is thanks to your above suggestion :)
@Sideshow: I have suggested to do that from begging! but you didn't applied!
@Akam Sorry, it was really hard to read in the comment. And you didn't use real_escape_string(), which is needed to avoid SQL injection.
@Akam I couldn't tell what you were using as the argument to join(), the single and double quotes look alike in the tiny comment font.
@Akam - There were quite a few suggestions to trial and they came thick and fast - got a bit confusing at some point :) Thanks for your help though.
0
$query="SELECT agent_id FROM agent_coverage WHERE primary_area LIKE '$search_term%'";
$result=mysqli_query($dbc, $query) or die("Could not obtain primary area coverage2");

$agent_primary=array();    

while($r=mysqli_fetch_array($result))
{
  array_push($agent_primary,$r['agent_id']);
}

then

if(!empty($agent_primary))
{
$ids=$agent_primary;
$query5="SELECT * FROM detail_db WHERE user_id IN($ids)";
$result5=mysqli_query($dbc, $query5) or die("Could not do SELECT");

while($row=mysqli_fetch_array($result5))
{
//do stuff with results here.
}
}

use this. I think it will help you.

3 Comments

How can that work? $ids is an array, so it will just interpolate the word Array.
plz see full code. in my code here is also array_push($agent_primary,$r['agent_id']); this code
That just adds an element to the array, just like the original $agent_primary[] = $r['agent_id'];. It's still an array. IN requires a comma-separated list.
0

You can do it like this

if(!empty($agent_primary))
{
    $ids=implode($agent_primary,",");
    $query5="SELECT * FROM detail_db WHERE user_id IN ($ids)";
    $result5=mysqli_query($dbc, $query5) or die("Could not do SELECT");

    while($row=mysqli_fetch_array($result5))
    {
    //do stuff with results here.
    }
}

Hope this Helps

Comments

0

edit: Both queries can be combined with a JOIN stament

$query = "
    SELECT
        dd.user_id,
        dd.foo
    FROM
        tmp_agent_coverage as ac
    LEFT JOIN
        tmp_detail_db as dd
    ON
        ac.agent_id=dd.user_id
    WHERE
        ac.primary_area LIKE '$search_term%'
";
$result=mysqli_query($dbc, $query) or mysqliError($dbc, "Could not obtain primary area coverage2");
while($r=mysqli_fetch_array($result))
{
    echo $r['user_id'], ' ', $r['foo'], "\n";
}

edit2: self-contained example

<?php
$dbc = new mysqli('localhost', 'localonly', 'localonly', 'test');
if ($dbc->connect_error) {
    var_dump($mysqli->connect_errno, $mysqli->connect_error);
    die;
}
setup($dbc);
$search_term = 'xy';

$query = "
    SELECT
        dd.user_id,
        dd.foo
    FROM
        tmp_agent_coverage as ac
    LEFT JOIN
        tmp_detail_db as dd
    ON
        ac.agent_id=dd.user_id
    WHERE
        ac.primary_area LIKE '$search_term%'
";
$result=mysqli_query($dbc, $query) or mysqliError($dbc, "Could not obtain primary area coverage2");
while($r=mysqli_fetch_array($result))
{
    echo $r['user_id'], ' ', $r['foo'], "\n";
}

define('DEVELOPMENT_DEBUG_MESSAGES', 1);
function mysqliError($dbc, $description) {
    if ( !defined('DEVELOPMENT_DEBUG_MESSAGES') || !DEVELOPMENT_DEBUG_MESSAGES ) {
        echo '<div class="error">', htmlspecialchars($description), '</div>';
    }
    else {
        echo '<fieldset class="error"><legend>', htmlspecialchars($description), '</legend>',
            htmlspecialchars($dbc->error), '</div>';
    }
}

function setup($dbc) {
    $q = array(
        'CREATE TEMPORARY TABLE tmp_agent_coverage (
            agent_id int auto_increment,
            primary_area varchar(32),
            primary key(agent_id),
            key(primary_area)
        )',
        "INSERT INTO tmp_agent_coverage (primary_area) VALUES ('xy1'),('dfg'),('xy2'),('abc'),('xy3')",
        'CREATE TEMPORARY TABLE tmp_detail_db (
            user_id int auto_increment,
            foo varchar(32),
            primary key(user_id)
        )',
        "INSERT INTO tmp_detail_db (foo) VALUES ('fooxy1'),('foodfg'),('fooxy2'),('fooabc'),('fooxy3')"
    );
    foreach($q as $query) {
        $dbc->query($query) or die(__LINE__ .' '.$query. ' '. $dbc->error);
    }
}

prints

1 fooxy1
3 fooxy2
5 fooxy3

original answer:
mysqli::query returning false means that an error occured while executing the query. That could be e.g. a syntax error or privileges or ... or ...
The error and errno properties of your $dbc object should hold more detailed information about the error. But you shouldn't show the complete error message to just any arbitrary user.
So, for debugging purposes define a function like

define('DEVELOPMENT_DEBUG_MESSAGES', 1);
function mysqliError($dbc, $description) {
    if ( !defined('DEVELOPMENT_DEBUG_MESSAGES') || !DEVELOPMENT_DEBUG_MESSAGES ) {
        echo '<div class="error">', htmlspecialchars($description), '</div>';
    }
    else {
        echo '<fieldset class="error"><legend>', htmlspecialchars($description), '</legend>',
            htmlspecialchars($dbc->error), '</div>';
    }
}

and then use this function in your code like

<?php
define('DEVELOPMENT_DEBUG_MESSAGES', 1);
[...]
$query="SELECT agent_id FROM agent_coverage WHERE primary_area LIKE '$search_term%'";
$result=mysqli_query($dbc, $query) or mysqliError($dbc, "Could not obtain primary area coverage2");

remove the define(...) line when you're done debugging.

Comments

0

Use implode to create a string and append brackets around it.

Get values of ids in a array and then implode it. Just see below example - This works.

 $arr = array(1,297,298);
    $new = '(';
    $new .= implode(',',$arr);
    $new .= ')';
    $query = "Select * from wp_posts where ID IN $new";

1 Comment

Yes - it gets an array of all the agent ids that match a certain criteria
0

try this

 $ids=join("','", $agent_primary);
 $query5="SELECT * FROM detail_db WHERE user_id IN('$ids')";

i tried it in my localhost and it works perfect!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.