修订问题:
如何在填写表单时引用一行MySQL数据。换句话说,使用my(' Select * FROM ...如何指定用于提取字段的行而无需处理表单以获取PHP字段?
所需流程1)用户输入第一个值,2)边栏MySQL查询查找该值并使用该行中的数据填充div,3)用户继续填写表格,同时能够看到提交MySQL数据的div
原始问题:
我很好奇你是否可以在MySQL查询中包含对HTML输入的引用。
以下面的例子为例。
('SELECT * FROM MyTableName WHERE MyColumnID="MyHTMLInputValue"');
我想根据输入字段的值引用行中的所有字段,而不确定如何引用这样的查询。
谢谢!
答案 0 :(得分:1)
Ajax是要走的路。
此示例使用jQuery。
首先,我们需要设置一个php脚本来获取我们的值并搜索它,然后返回我们的数据。
PHP myPhpScript.php
<?php
$search_value = $_POST["field1"]; //Get our value from the post.
//Make sure to do some authentication on the value so that bad values dont get through
$connection = new mysqli(Stuff here);
$rows = $connection->query(
"SELECT * FROM someTable where searchColumn LIKE %".$search_value."%"
);
//Now all we need to do is send out our data. Lets use json.
$out = $rows[0];//Get the first row. NOTE: Make sure to remove any columns that you dont want the client to see.
echo json_encode($out); //Send the client the data.
?>
Javascript Some script on the page.
var textbox = $("#mySearchBox"); //This is the jQuery object for our text box.
var viewbox = $("#myViewer"); //This is the jQuery object for the div that holds the results
textbox.on("input", function () {
$.ajax({
url: "myPhpScript.php", //This is the php script that we made above.
method: "POST", //This set our method to POST.
data: {field1: textbox.val()}, //set the textbox value to field1
dataType: "json", //So jquery formats the json into an object.
success: function (phpDataObject) { //Now its up to you to decide what to do with the data. Example below
viewbox.html("");//Clear the viewbox.
viewbox.append("Id: "+phpDataObject["id"]); //Show the id of row that was found.
}
});
});
此代码可能无效。只需修复出现的任何语法错误。
希望这有帮助。
如果您需要更多帮助,请发表评论。
答案 1 :(得分:0)
这听起来不是一个好主意。通常,您希望在站点和数据库之间进行一些分离。您可以接受&#34; MyHTMLInputValue&#34;,处理它,然后您就可以完成查询。
var myValue = MyHTMLInputValue;
//validate input
('SELECT * FROM MyTableName WHERE MyColumnID="' + myValue + '"')