我有一个简单的登录,当用户登录时,他们可以上传标题和评论(以及图像,但我们可以忽略它,因为这可以正常)到数据库。我想要的是当前登录的人的用户ID也插入到数据库中。这是我目前的代码
的login.php
<?php
session_start();
if(isset($_SESSION["user"])){
header("location:index.php");
exit();
}
?>
<?php
if(isset($_POST["username"]) && isset($_POST["password"])){
// Filter everything except letters and numbers
$user = preg_replace('#^A-Za-z0-9#i','',$_POST["username"]);
$password = preg_replace('#^A-Za-z0-9#i','',$_POST["password"]);
// Connect to mySQL
include"assets/scripts/sql_connect.php";
// Query the person
$sql = $conn->query("SELECT id FROM user_login WHERE user_name='$user' AND user_password='$password' LIMIT 1");
// Make sure person exists
$existCount = $sql->rowCount();
// Evaluate the count
if($existCount == 1){
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
}
$_SESSION["id"] = $id;
$_SESSION["user"] = $user;
$_SESSION["password"] = $password;
header("location:index.php");
exit();
}else{
echo"Login details incorrect, try again <a href='index.php'>Click here</a>";
exit();
}
}
?>
upload.php的
<?php
session_start();
include"assets/scripts/sql_connect.php";
if (isset($_POST['image_title'])){
$userid = $_SESSION["id"];
$image_title = $_POST['image_title'];
$image_comment = $_POST['image_comment'];
//Add image text to the database
$sql = $conn->query("INSERT INTO user_image(user_id,image_title,image_comment, image_date_added) VALUES('$userid','$image_title','$image_comment', now())") or die(mysql_error());
$id = $conn->lastInsertId();
$image_id = $conn->lastInsertID();
// Places image in the images folder
$new_name = "$image_id.jpg";
move_uploaded_file($_FILES['app_art_image']['tmp_name'],"appArtImages/$new_name");
header("location:gallery.php");
exit();
}
?>
我得到的问题是,无论用户登录了什么,都会在user_image数据库的user_id字段中插入0。
答案 0 :(得分:1)
使用mysql_fetch_assoc()
代替mysql_fetch_array()
试试
if($existCount == 1){
while($row = mysql_fetch_assoc($sql)){
$id = $row["id"];
$_SESSION["id"] = $id;
break;
}
$_SESSION["user"] = $user;
$_SESSION["password"] = $password;
header("location:index.php");
exit();
}else{
echo"Login details incorrect, try again <a href='index.php'>Click here</a>";
exit();
}
希望它有所帮助:)
答案 1 :(得分:1)
有人解决它。我改变了
while($row = mysql_fetch_array($sql)){
在login.php中
while($row = $result->fetch(PDO::FETCH_ASSOC)){