我想执行一个我保存在数据库中的查询,如下所示:
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中是一个菜鸟,所以请解释它是否可行。
答案 0 :(得分:0)
如果您确实创建了存储过程/函数,则只需使用:
mysql_query("Call procedure_name(@params)")
这会起作用。请参考此处:http://php.net/manual/en/mysqli.quickstart.stored-procedures.php
答案 1 :(得分:0)
如果我理解正确,您可以将查询保存在表格中的数据库中,并且要执行这些查询。
解决问题:你有两个任务要做:
这有点元,但是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]);
?>
答案 2 :(得分:0)
查询表以获取查询,然后执行该查询并循环结果并输出字段
<?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";
}
}
}
?>
答案 3 :(得分:0)
只需打开表格,然后在
等变量中获取单个查询$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
子句选择查询。