我想在数据库中执行一个保存的查询


i want to execute a saved query in the database

我想执行一个查询,我保存在我的数据库中,像这样:

ID | NAME          | QUERY
 1 | show_names    | "SELECT names.first, names.last FROM names;"
 2 | show_5_cities | "SELECT cities.city FROM city WHERE id = 4;"

这可能吗?我对php有点陌生,所以请解释一下如果可能的话。

如果我理解正确的话,您将查询保存在数据库中的表中,并且要执行这些查询。

把问题分解:你有两个任务要做:

  1. 为要运行的查询查询数据库。
  2. 执行该查询。

这是一个有点元,但meh:)

警告:PHP中的mysql_函数已弃用,如果被错误的人使用可能会很危险。

<?php
if (!$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')) {
    die('Could not connect to mysql');
}
if (!mysql_select_db('mysql_dbname', $link)) {
    die('Could not select database');
}
$name   = "show_5_cities"; // or get the name from somewhere, e.g. $_GET.
$name = mysql_real_escape_string($name); // sanitize, this is important!
$sql    = "SELECT `query` FROM `queries` WHERE `name` = '$name'"; // I should be using parameters here...
$result = mysql_query($sql, $link);
if (!$result) {
    die("DB Error, could not query the database'n" . mysql_error(););
}
$query2 = mysql_fetch_array($result);
// Improving the code here is an exercise for the reader.
$result = mysql_query($query2[0]);
?>

如果您创建了一个存储过程/函数,您可以简单地使用:

mysql_query("Call procedure_name(@params)")

那就行了。此处参考:http://php.net/manual/en/mysqli.quickstart.stored-procedures.php

查询表以获取查询,然后执行该查询并循环遍历结果并输出字段

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) 
{
    printf("Connect failed: %s'n", mysqli_connect_error());
    exit();
}
$RequiredQuery = intval($_REQUEST['RequiredQuery']);
$sql    = "SELECT `QUERY` FROM QueryTable WHERE ID = $RequiredQuery";
$result = mysqli_query($link, $sql);
if ($row = mysqli_fetch_assoc($result)) 
{
    $sql    = "SELECT `QUERY` FROM QueryTable WHERE ID = $RequiredQuery";
    $result = mysqli_query($link, $row['QUERY']);
    while ($row2 = mysqli_fetch_assoc($result)) 
    {
        foreach($row2 AS $aField=>$aValue)
        {
            echo "$aField 't $aValue 'r'n";
        }
    }
}
?>

只需打开Table并在变量中获取单个查询,例如

$data = mysql_query('SELECT * FROM <the Table that contains your Queries>');
while(($row = mysql_fetch_row($data)) != NULL)
{
    $query = $row['Query'];
    mysql_query($query);   // The Query from the Table will be Executed Individually in a loop
}

如果要从表中执行单个查询,则必须使用WHERE Clause选择查询。