我整晚都在努力解决这个问题,但我似乎无法解决这个问题。我是php和PDO的新手。我成功创建了包含字段id
,firstname
和lastname
的数据库。
在id =1
上,用户名和姓氏的值为Andrea
和Bocelli
,
id=2
上Sarah
和Brightman
。
现在我想获取id1上的所有firstname和lastname并将其存储在$ _SESSION数组变量中,并在anoter $ _SESSION数组变量中存储id2的firstname和lastname值,以便我能够访问这些变量其他页面。这是我的代码:(已经编辑和工作)
$host = "localhost";
$dbname = "try";
$user = "root";
$pass = "";
$dbh = new PDO("mysql:host=$host;dbname=$dbname",$user,$pass);
$statement = $dbh->prepare('SELECT * FROM members');
$statement->execute();
$count = $statement->rowCount();
$_SESSION['firstname']=array();
$_SESSION['lastname']=array();
for ($c=0, $c2=1;$c<$count;$c++, $c2++){
$sql='SELECT firstname FROM members WHERE id=?';
$sth=$dbh->prepare($sql);
$sth->execute(array($c2));
$_SESSION['firstname'][$c]=$sth->fetchColumn();
$sql='SELECT lastname FROM members WHERE id=?';
$sth=$dbh->prepare($sql);
$sth->execute(array($c2));
$_SESSION['lastname'][$c]=$sth->fetchColumn();
}
现在的问题是这段代码只获取id1上的数据,显然我只访问了循环内的id 1。我想要做的是id号将增加每个循环。我尝试在循环外部声明变量$idupdate
,在部分WHERE id=$idupdate
然后&idupdate++
的循环内声明,但它似乎不起作用。我想要实现的是获取id 1中整个列中的所有数据,并将其存储在另一页上可访问的数组变量中。我怎样才能做到这一点?非常感谢任何帮助。
答案 0 :(得分:0)
你需要调用session_start();在设置/访问任何会话变量之前。 然后你可以通过首先调用sesion_Start();
再次访问另一个页面中的会话变量完成后,调用session_destroy();
答案 1 :(得分:0)
您不必将会话声明为数组。 尝试这样的事情。
$_SESSION['id1']['firstname']=$firstname_id1; //
$_SESSION['id1']['lastname']=$lastname_id1;
$_SESSION['id2']['firstname']=$firstname_id2;
$_SESSION['id2']['lastname']=$lastname_id2;
您正在做的事情将覆盖名字和姓氏。
$_SESSION['firstname'][$c]=$sth->fetchColumn();
我看到你的for循环没有多大意义。这样的事情怎么样。
<?php
session_start();
$host = "localhost";
$dbname = "try";
$user = "root";
$pass = "";
$dbh = new PDO("mysql:host=$host;dbname=$dbname",$user,$pass);
$sql='SELECT firstname,lastname FROM members WHERE id=1';
$sth=$dbh->prepare($sql);
$sth->execute();
$_SESSION[]['firstname']=$sth->fetchColumn();
$_SESSION[]['lastname']=$sth->fetchColumn(1);
$sql='SELECT firstname,lastname FROM members WHERE id=2';
$sth=$dbh->prepare($sql);
$sth->execute();
$_SESSION[]['firstname']=$sth->fetchColumn();
$_SESSION[]['lastname']=$sth->fetchColumn(1);
?>
编辑:
插入行时存储名字和姓氏。
<?php
session_start();
$firstname = 'Mike';
$lastname = 'Luther';
// query
$sql = "INSERT INTO members (firstname,lastname) VALUES (:firstname,:lastname)";
$q = $conn->prepare($sql);
$q->execute(array(':firstname'=>$firstname,
':lastname'=>$lastname));
$id = $db->lastInsertId('id');
$_SESSION[$id]['firstname'] = $firstname;
$_SESSION[$id]['lastname'] = $lastname;
//i dont think you will need that $id variable. What i understand is that you just want to display the firstname and lastname.
//you can just write
$_SESSION['firstname'] = $firstname;
$_SESSION['lastname'] = $lastname;
?>