使用Dropdown动态显示内容(连接到数据库)

时间:2015-12-13 18:47:17

标签: javascript ajax dropdown

我很喜欢这个东西,我只是尝试用Javascript和PDO和PHP做一个AJAX请求来创建一个动态反应的下拉函数,以显示新的内容..因为我的知识非常有限,我在这里创建了它通过组合我从各种页面和视频获得的代码片段。错误是:

Parse error: syntax error, unexpected 'endforeach' (T_ENDFOREACH) in /var/www/xxx/html/listing.php on line 22

这是我的listing.php页面,其中应显示下拉列表和新内容:

<!DOCTYPE html>
<html>

<head>
<title>listing</title>

<meta charset="UTF-8">
<meta name="description" content="">
<meta name="author" content="">
<meta name="keywords" content="">

<link href=".css" type="text/css" rel="stylesheet">
<link href="favicon.ico" type="image/x-icon" rel="shortcut icon">
</head>

<body>

<select name="user" id="user-select">

<option value="">Choose a user</option>
<?php foreach ($subjects->fetchAll() as $user); ?>
  <option value="<?php echo $user['subject_id']; ?>"><?php echo $user['subject']; ?></option>
<?php endforeach; ?>

</select>

<div id="user-profile"></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="js/global.js"></script>

   

这是global.js文件:

$('#user-select').on('change', function() {
var self = $(this);

$.ajax({
    url: 'https://www.xxx.de/partials/user.php',
    type: 'GET',
    data: { user: self.val() },
    success: function(data){
      $('#user-profile').html(data);
    }
});
});

partials / user.php,它包含与数据库的连接:

<?php
$dsn = "xxx";
$user = "xxx";
$pw = "xxx";

try {
$pdo = new PDO($dsn, $user, $pw);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}

if (isset($_GET['user'])) {
$userQuery = "
SELECT
    subjects.subject_id,
    subjects.subject,
FROM subjects
WHERE subjects.subject_id = :subject_id
";

$user = $pdo->prepare($userQuery);
$user->execute(['subject_id' => $_GET['user']]);

$selectedUser = $user->fetch(PDO::FETCH_ASSOC);

print_r($selectedUser);
}
?>

感谢任何帮助,我感谢任何提示!

2 个答案:

答案 0 :(得分:1)

愚蠢的错误..我只是忘了在listing.php页面上包含连接来填充foreach循环。 - &GT;

在!DOCTYPE html开始之前的listing.php上:

{{1}}

答案 1 :(得分:0)

尝试更换; with:在php foreach语句中

<?php foreach ($subjects->fetchAll() as $user): ?>