使用$变量查询

时间:2013-04-27 04:30:33

标签: php mysql variables drop-down-menu

我一直在尝试各种各样的事情,出于某种原因,无论我做什么,我似乎无法用一个可用的查询...到目前为止,这是我的代码,它不是全部,但我的针指向我的地方问题是......

<?php




    $hostname = 'localhost';        // Your MySQL hostname. Usualy named as 'localhost', so you're NOT necessary to change this even this script has already online on the internet.
 $dbname   = 'ServiceHistoryDB'; // Your database name.
 $username = 'root';             // Your database username.
 $password = '';                 // Your database password. If your database has no password, leave it empty.

// Let's connect to host
 mysql_connect($hostname, $username, $password) or DIE('Connection to host is failed, perhaps the service is down!');
 // Select the database
 mysql_select_db($dbname) or DIE('Database name is not available!');

$custnum = '1'; 

    function connect(){

        mysql_connect($hostname, $username, $password) or DIE('Connection to host is failed, perhaps the service is down!');
        mysql_select_db($dbname) or DIE('Database name is not available!');
    }

    function close(){
        mysql_close();
    }

        function query(){
            $mydata = mysql_query("SELECT * FROM vehicles WHERE CustNum=1");
            while($record = mysql_fetch_array($mydata)){
                echo '<option value="' . $record["Model"] . '">' . $record["Model"] . '</option>';
        }

    }










?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>testdropdown</title>
</head>

<body>

<select name="dropdown">
<?php query() ?>
</select>
<?php close() ?>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

好吧,你可以简单地写下面的变量:

$variable = 'someData';
"Select someColumn from yourTable where someColumn = $variable";

但是,如果您是通过函数执行此操作,则可能需要声明global变量以检索值 如果 ,则将值设置为外部功能:

function someFunc(){
    global $variable; // set above
    "Select someColumn from yourTable where someColumn = $variable";
}

使用预准备语句

您应该切换到mysqli prepared statements,因为它们更安全:

if($stmt = $mysqli->prepare($yourSQL)){
    $stmt->bind_param("s", $variable);
    $stmt->execute();
    $stmt->bind_result($thisHoldsThe_QueryResult);
    $stmt->fetch();
    $stmt->close();
}