我要获得想要的结果最困难。我做了很多研究,但还没有得到。我对此很陌生,但是在发布此问题之前进行了研究。
好的,所以我有一个包含以下列的表:user_id,my_music,my_movies,my_weather,my_maps和my_news
除user_id之外的每一列都将具有1或0。我需要做的是找出数据库中针对特定用户的每一列所存储的值。
这是我到目前为止的内容-这是我的config.php:
// These variables define the connection information for your MySQL database $username = "dbo12345"; $password = "xxxxxx"; $host = "db12345.db.123.com"; $dbname = "db12345"; $options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'); try { $db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options); } catch(PDOException $ex){ die("Failed to connect to the database: " . $ex->getMessage());} $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); header('Content-Type: text/html; charset=utf-8'); session_start();
这是我的admin.php文件:
require("config.php"); if(empty($_SESSION['user'])) { header("Location: index.php"); die("Redirecting to index.php"); } $userid = $_SESSION['user']['id']; $sql = "SELECT my_music, my_movies, my_weather, my_maps, my_news FROM user_preferences WHERE user_id = :userID"; //Note the removed semi-colon that was probably causing your error $stmt = $db->prepare($sql); $stmt = $db->bindParam(":userID", $userid); $userid = $_SESSION['user']['id']; $sql = "SELECT my_music, my_movies, my_weather, my_maps, my_news FROM user_preferences WHERE user_id = :userID"; //Note the removed semi-colon that was probably causing your error $stmt = $db->prepare($sql); $stmt->bindParam(":userID", $userid, PDO::PARAM_INT); $stmt->execute(); $result = $stmt->fetch(); if ($result['my_music']) { $musicChecked = 'checked="checked"'; } else { $musicChecked = ''; } if ($result['my_movies']) { $checked = 'checked="checked"'; } else { $checked = ''; }
我如何以不同的方式编写上面的代码?我知道有一种方法,但是我很难找到它。
根据上面的结果,我需要更新一些复选框,例如,如果数据库中my_music为1,则将复选框设置为“ checked”。所以我这样做:
<input type="checkbox" name="mymusic" id="mymusic" <? echo $musicChecked;?> /> <input type="checkbox" name="mymovies" id="mymovies" <? echo $moviesChecked;?> />
如果我需要添加更多信息,请告诉我。任何帮助都将不胜感激。
您真的很接近,您无法正确获取:
require("config.php"); if(empty($_SESSION['user']['id'])) { header("Location: index.php"); die("Redirecting to index.php"); } $userid = $_SESSION['user']['id']; $sql = "SELECT my_music, my_movies, my_weather, my_maps, my_news FROM user_preferences WHERE user_id = :userID"; $stmt = $db->prepare($sql); $stmt->bindParam(":userID", $userid); $stmt->execute(); $result = $stmt->fetch();
var_dump
echo
<input id="mymusic" type="checkbox" name="mymusic" <?php echo ($result['my_music']==1 ? 'checked' : '');?> /> <input id="mymovies" type="checkbox" name="mymovies" <?php echo ($result['mymovies']==1 ? 'checked' : '');?> />