【问题标题】:Add/attach a UserID based on Session PHP添加/附加基于会话 PHP 的用户 ID
【发布时间】:2019-02-21 15:06:07
【问题描述】:

希望将基于会话变量的 UserID 添加到此 post 方法。

我可以根据会话 ID 显示日记帖子,但希望每次发布条目时将用户 ID 实际添加到相应的表中。

我在下面包含了数据库的图片和已经添加帖子的插入查询。

日记和 tblUseraccount 已经使用外键链接

PHP 函数

<?php
if(session_id() == '') {
	session_start();
        
}



if(!isset($_SESSION['myEmail'])){ //if login in session is not set
    header("Location: login.php");
}

 if (!isset($_SESSION['myEmail'])) {
		echo"  <a href='login.php'";
	  }
	  else {
             $myFName = $_SESSION['userFirstName'];
          }

我也想插入 UserID 的代码

<?php
// post_add.php
if(!empty($_POST)) {
    include 'mysql.php';
    if(mysql_safe_query('INSERT INTO posts (title,body,date,) VALUES (%s,%s,%s)', $_POST['title'], $_POST['body'], time()))
        echo 'Entry posted. <a href="post_view.php?id='.mysql_insert_id().'">View</a>';
    else
        echo mysql_error();
}
?>

mysql.php 部分

<?php
// mysql.php
function mysql_safe_string($value) {
    $value = trim($value);
    if(empty($value))           return 'NULL';
    elseif(is_numeric($value))  return $value;
    else                        return "'".mysql_real_escape_string($value)."'";
}
function mysql_safe_query($query) {
    $args = array_slice(func_get_args(),1);
    $args = array_map('mysql_safe_string',$args);
    return mysql_query(vsprintf($query,$args));
}
function redirect($uri)
{
    if (!headers_sent())
    {    
        header('Location: '.$uri);
        exit;
        }
    else
        {  
        echo '<script type="text/javascript">';
        echo 'window.location.href="'.$uri.'";';
        echo '</script>';
        echo '<noscript>';
        echo '<meta http-equiv="refresh" content="0;url='.$uri.'" />';
        echo '</noscript>'; exit;
    }
}
@mysql_connect('localhost','######','#######');
@mysql_select_db('######');

enter image description here

enter image description here

【问题讨论】:

  • 另外,请使用 mysqli 或 pdo 代替 mysql,因为它已被弃用
  • 请查看我的回答 John,如果您有任何不明白的地方,请回复我
  • @edisoni.1337 它显示的列数与第 1 行的值计数不匹配

标签: php variables session


【解决方案1】:

首先你需要在 session 中设置 UserId 当您进行用户登录时,您可以在会话中添加用户 ID,就像您添加了 userFirstName

之后,您可以在文件中启动会话,然后在要插入帖子时从会话中获取用户 ID

session_start();

if(!empty($_POST)) {
    include 'mysql.php';

    $userId = $_SESSION['UserID']; //or whatever is your key in session where you store the user id

    if(mysql_safe_query('INSERT INTO posts (title,body,date,UserID) VALUES (%s, %s, %s, %s)', $_POST['title'], $_POST['body'], time(), $userId)){
        echo 'Entry posted. <a href="post_view.php?id='.mysql_insert_id().'">View</a>';
    }else{
        echo mysql_error();
    }
}

我还注意到您正在使用mysql_query 来运行您的查询。您应该使用mysqli_queryPDO,因为mysql_query 在PHP 5.5 中被弃用,在PHP 7 中被删除

您可以在php页面here阅读更多内容

【讨论】:

  • 列数与第 1 行的值数不匹配
  • 因为我忘记在 VALUES 处添加“%s”。 @John 请再次检查更新的答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-30
  • 2015-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-14
相关资源
最近更新 更多