此问题已经在这里有了答案:
<?php
$dbh = new PDO("mysql:host=localhost;dbname=myDb", "root", "");
$sh_addr='Whole Address here';
echo $sh_addr; //here $sh_addr echos 'Whole Address here'
$stat = $dbh->prepare("select * from jobs where sh_addr='$sh_addr'");
$stat->execute();
while($row = $stat->fetch()){
echo "<td>".$row['id']."</td>";
}
然后,我从while循环中得到结果
但是...我试图将变量$ sh_addr值与$ sh_addr = Auth :: user()-> sh_addr一起使用;
但是while循环对此没有输出
<?php
$dbh = new PDO("mysql:host=localhost;dbname=myDb", "root", "");
$sh_addr= Auth::user()->sh_addr;
echo $sh_addr; //here $sh_addr echos Auth user Address successfully..
$stat = $dbh->prepare("select * from jobs where sh_addr='$sh_addr'");
$stat->execute();
while($row = $stat->fetch()){
echo "<td>".$row['id']."</td>";
}
但是我没有从while循环中得到结果
我希望使用$sh_addr= Auth::user()->sh_addr;
获得输出,因为该地址对于不同的经过身份验证的用户将是动态的。我在做什么错?
考虑到查询,您应该使用bindValue(...)
或bindParam(...)
方法:
$stat = $dbh->prepare('SELECT * FROM jobs WHERE sh_addr=:address');
$stat->bindValue(':address', $sh_addr);
$stat->execute();
$rows = $stat->fetchAll();
foreach ($rows as $row) {
// ...
}
$stat->debugDumpParams();
这是单个PHP文件示例(不刷新整个页面),但是您可能需要更改零件YOUR_DATA_HERE
,DATABASE_NAME_HERE
以及root
(这是PhpMyAdmin
中的用户名)。
<?php
if (isset($_POST['submit'])) {
// Escape possible HTML tags:
$content = htmlspecialchars($_POST['myContent'], ENT_QUOTES | ENT_SUBSTITUTE);
// Database connection.
// (Allows data to take 64 KB using "65536" constant)
$db = new PDO('mysql:dbname=DATABASE_NAME_HERE', 'root', '');
$db->query('CREATE TABLE IF NOT EXISTS `my_table` (id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL, text VARCHAR(65536))');
// Storing new record.
$query = $db->prepare('INSERT INTO my_table VALUES (NULL, :text)');
$query->bindValue(':text', $content);
if ($query->execute()) {
$response = 'Successfully stored: ' . $content;
}
else {
$response = 'Error: ' . join(' ', $query->errorInfo());
}
exit($response);
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('form#my_form_id').submit(function(e) {
e.preventDefault();
var myContent = "YOUR_DATA_HERE";
var url = '#';
$.post(url, {'submit': true, 'myContent': myContent}, function(response) {
alert(response);
});
});
});
</script>
</head>
<body>
<div id="center" style="text-align: center; margin-top: 150px;">
<form id="my_form_id">
<input type="submit" name="Send">
</form>
</div>
</body>
</html>
[Note:您在查询中写入一个占位符(例如
:text
),然后分配诸如->bindValue(':text', $your_variable_here);
的值。