2017-09-02 69 views
0

我使用php创建了一个搜索,这样当用户登录后,他们可以搜索其他用户并将其添加为朋友。当用户单击添加为朋友按钮时,我想将搜索结果中登录的用户的用户名和用户的用户名发布到名为friend_request的数据库表中。在php中发布搜索结果

这里是我的代码

<?php 
 
if(isset($_POST['search'])) { 
 
    $search = $_POST['search']; 
 
    $search = preg_replace("#[^0-9a-z]i#","", $search); 
 
    
 
$search = "%$search%"; 
 

 
if ($stmt = $db->prepare("SELECT username, name, location, gender, date_of_birth, url FROM Users WHERE name LIKE ?")){ 
 
    $stmt->bind_param("s", $search); 
 
    $stmt->execute(); 
 
    $stmt->bind_result($username, $name, $location, $gender, $date_of_birth, $picture); 
 
    $stmt->store_result(); 
 
    $count = $stmt->num_rows; 
 

 
    if ($count == 0) { 
 
     $output = "There was no search results!"; 
 
    } else { 
 
    
 

 
     while ($stmt->fetch()) { 
 

 
       
 
      $output .='<form action="#" method="post"><div class="row"><div class="col-sm-3">'.$name.'<br>'.$location.'<br>'.$gender.'<br>'.$date_of_birth.'</div>'; 
 

 
      $output2 = '<div class="col-sm-3"><img src="upload/'.$picture.'"width="180" height="144" /></div>'; 
 

 
      $output3 = '<input type="submit" name="addfriend" value="Submit" /></div></form>'; 
 
      
 

 
     } 
 
    } 
 
} 
 
} 
 

 

 
    if(isset($_POST['addfriend'])) { 
 
    
 

 
    $user_from = $_SESSION['username']; 
 
    $user_to = $_POST['username']; 
 

 

 
if ($stmt = $db->prepare("INSERT INTO `friends_request`(`user_to`, `user_from`) VALUES (?,?)")){ 
 
    $stmt->bind_param("ss", $user_to, $user_from); 
 
    $stmt->execute(); 
 

 

 
} 
 
} 
 

 
?>

当我运行我的代码,我得到以下信息

注意:未定义指数:用户名/应用程序/ MAMP/htdocs目录第51行的/student_connect/header.php

+0

你是否开始在任何地方开会?做'session_start();'开始会话。 –

+0

我在我的代码的开头有它,但我没有复制 – Rebekah

+0

[PHP:“注意:未定义的变量”,“注意:未定义的索引”和“注意:未定义的偏移量”](https:/ /stackoverflow.com/questions/4261133/php-notice-undefined-variable-notice-undefined-index-and-notice-undef) –

回答

0

很简单。 它说$ _SESSION ['username'];尚未设置,因此请查找您希望设置的代码行。我想这可能是一些其他的文件(也许到一个登录表单填写后执行..?)

+0

它实际上是这条线,它不喜欢$ user_to = $ _POST ['username']; – Rebekah

+0

对不起!不过,根据你输入的代码,$ _POST ['username']可能在下面。这意味着用户提交到页面的表单可能没有“用户名”字段,因此您必须在te表单内编写它。如果我的代码正确(不确定),你需要在$ output3的开头:'',otherwhise submitting add friends will pass那$的用户名到页面 –

+0

我不想输入用户名 – Rebekah

0

你需要开始代码调试.....

尝试增加后“这一行$ user_from = $ _SESSION ['username'];“

if(!$user_from) 
{ 
    echo "<pre>"; 
    var_dump($_SESSION); 
    echo "<pre>"; 
} 

运行你的代码,结果贴在这里 - 然后我们就可以开始确定哪些信息是在会议期间举行。

这是你不得不做的事情,当代码没有做到预期的时候,检查你的变量,看看有什么缺少之前,前往堆栈。我们在这里提供帮助,但需要所有可能的信息。

+0

刚刚看到您的评论re $ _POST ['username'] .. change var_dump($ _ SESSION);在我对var_dump($ _ POST)的回答中; – Nick

+0

这是它显示数组(1){[“addfriend”] =>字符串(6)“提交”} – Rebekah

+0

然后你没有在你的表单中定义你的POST变量的用户名。您需要查看定义将信息发送到此提交脚本的表单的HTML。 – Nick