在PHP文件中,任何人都可以帮我直接制作一个for循环,我不知道将要选择的行数。
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydb";//database details
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM mytable";
$result = $conn->query($sql);
$myarray = array();
$index = 0;
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc())
{
$myarray[$index] = $row["firstname"];
$index++;
$myarray[$index] = $row["lastname"];
$index++;
$myarray[$index] = $row["email"];
$index++;
}
}
else
{
echo "0 results";
}
$conn->close();
?>
Javascript代码包含搜索栏建议代码的javascript,这里我没有提到typeahead javascript文件
var substringMatcher = function(strs) {
return function findMatches(q, cb) {
var matches, substringRegex;
// an array that will be populated with substring matches
matches = [];
// regex used to determine if a string contains the substring `q`
substrRegex = new RegExp(q, 'i');
// iterate through the pool of strings and for any string that
// contains the substring `q`, add it to the `matches` array
$.each(strs, function(i, str) {
if (substrRegex.test(str)) {
matches.push(str);
}
});
cb(matches);
};
};
$('#the-basics .typeahead').typeahead({
hint: true, //here i used typeahead js code though i didnt mentioned here
highlight: true,
minLength: 1
}, {
name: 'states',
source: substringMatcher(states)
});
答案 0 :(得分:0)
当您读取值时,可以在这里简化PHP,因为您不需要增加索引:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydb";//database details
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);//making a connection
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM mytable";
$result = $conn->query($sql);
$myarray = array();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$myarray[] =$row["firstname"];
$myarray[] =$row["lastname"];//storing in the array
$myarray[] =$row["email"];
}
} else {
echo "0 results";
}
$conn->close();
?>
您可以将结果回显到您需要的Javascript,例如echo($myarray[0])
。
您的Javascript可能如下所示:
var matches = <?php echo($myarray[0]); ?>
答案 1 :(得分:-1)
您可以通过4种方式将动态内容插入到javascript代码中。
将javascript内联到您的PHP页面。也就是说,将您的js代码放在<script>
标记
使动态js变量全局化并在php页面中填充它们。您的单独JS文件将能够读取这些全局js变量。