简体   繁体   中英

MySQL PHP Get value from a database when knowint two other values in the same table

I have a MySQL table - In my problem I have two values which I know each in a separate column, but I need to find the 3 value based on the two values that I know and echo it.

This is what I tried but no luck:

<?php
...

$profile_url = 'xyz';

$pic_switch = array (
    '01' => mysql_query("SELECT mm_image_switch FROM $tbl_name04 WHERE profile_url = '$profile_url' AND mm_image_id ='01'")
    '02' => mysql_query("SELECT mm_image_switch FROM $tbl_name04 WHERE profile_url = '$profile_url' AND mm_image_id ='02'")
    '04' => mysql_query("SELECT mm_image_switch FROM $tbl_name04 WHERE profile_url = '$profile_url' AND mm_image_id ='04'")
...
?>

I want to get the value of the row mm_image_switch when the profile_url is xyz, and mm_image_id = 01, etc...

When I echo $pic_switch['01'] - i only get the profile_url value.

mysql_query() does not return the value of mm_image_switch , it returns a resource , something you will pass as parameter to other functions like mysql_fetch_row() to iterate through the results of this query. You have to do something more like this:

$res = mysql_query("SELECT mm_image_switch FROM ...");
$row = mysql_fetch_assoc($res);

if ($row !== FALSE) // if the query actually returned a matching row
{
    $pic_switch['01'] = $row['mm_image_switch'];
}
else
{
    $pic_switch['01'] = 'Not found';
}

But instead of doing one query for each ID, you can simply do this:

function get_pic_switches($profile_url, $ids)
{
    global $tbl_name04;

    $ret = array();
    $res = mysql_query("SELECT mm_image_id, mm_image_switch FROM $tbl_name04 WHERE profile_url = '$profile_url' AND mm_image_id IN ('".implode("', '", $ids)."')");

    while ($row = mysql_fetch_row($res))
    {
        $ret[$row[0]] = $row[1]; // $ret[mm_image_id] = mm_image_switch;
    }

    return $ret;
}

$pic_switch = get_pic_switches('xyz', array('01', '02', '04'));

Notice that the extension mysql_ is deprecated as of PHP 5.5.0 and will be removed in future versions of PHP. It is recommended that new code is written using one of its alternatives such as MySQLi or PDO .

mysql_query doesn't return a value but a result set which can be read with others functions like mysql_fetch_row, mysql_fetch_assoc, mysql_fetch_object or mysql_fetch_array for example. See the php documentation (php.net) to get more details.

Otherwise, I don't understand why execute all of your queries in an array and why do you use an array for the same query with differents params values.

NB : mysql_* functions are deprecated. Prefer use the equivalents mysqli_* functions or PDO.

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