How to use mySQL WHERE clause in PHP?

It seems that nothing is being transferred from the field securityinfo.

for ($k = 1; $k < $fieldscnt; $k++)
{
    $selectsecurityname = mysql_query("SELECT `security name` FROM securityinfo WHERE symbol = '$symbol[$k]'") or die(mysql_error());
    $securityname = mysql_fetch_array($selectsecurityname);
    $sym = $symbol[$k]

    echo "<td>$securityname[$sym]</td>";
}

Basically, I want to search for a string that has a match in a field symbol, and then returns a value from a field securityinfoin the same string.

+3
source share
4 answers

Beyond the answers of others fixing parts of your example, there is one more problem:
You (try) to grab the value from the table in your example. But when you use it, you refer to it as an array, while it is probably just a string (name).

A complete example with all corrected would look like this:

for ($k = 1; $k < $fieldscnt; $k++)
{
    $sym = mysql_real_escape_string($symbol[$k]);
    $selectsecurityname = mysql_query("SELECT `security name` FROM securityinfo WHERE symbol='$sym'") or die(mysql_error());
    $securitynamearray = mysql_fetch_array($selectsecurityname);
    $securityname = $securitynamearray['security name'];

    echo "<td>$securityname</td>";
}

PS , .

PPS mysql_fetch_row mysql_fetch_array ( ) , :

$securitynamerow = mysql_fetch_row($selectsecurityname);
$securityname = $securitynamerow[0];
0

PHP , . , , .

, escaping SQL, .

$selectsecurityname = mysql_query("
    SELECT `security name` FROM securityinfo 
    WHERE symbol = '" . mysql_real_escape_string($symbol[$k]) . "'") 
  or die(mysql_error());

, :

$sym = mysql_real_escape_string($symbol[$k]);
$selectsecurityname = mysql_query("
    SELECT `security name` FROM securityinfo 
    WHERE symbol = '{$sym}'") 
  or die(mysql_error());
+4

$securityname . , :

while ($row = mysql_fetch_array($selectsecurityname) {
  $myArray[] = $row;
}

$sym = $symbol[$k];
echo "<td>".$myArray[$sym]."</td>";

mysql_fetch_array() . : http://php.net/manual/en/function.mysql-fetch-array.php

+2

If you want to access the array indices in a string, enclose them in braces:

$a= array(
 'hello'=> 'world',
 'nice'=> 'one',
);

var_dump("This is the value of \$a['hello']: {$a['hello']}");

And rewrite your original statement as:

for ($k = 1; $k < $fieldscnt; $k++)
    {
    $selectsecurityname = mysql_query("SELECT `security name` FROM securityinfo WHERE symbol = '{$symbol[$k]}'") or die(mysql_error());
    $securityname = mysql_fetch_array($selectsecurityname);
    $sym = $symbol[$k]

    echo "<td>{$securityname[$sym]}</td>";

Of course, you need to make sure that it is $symbol[$k]properly escaped for use in the mysql statement.

0
source

Source: https://habr.com/ru/post/1728796/


All Articles