PHP:我有一个mvc模型:
public function addFriend($user)
{
$sth = $this->db->prepare('SELECT user_id FROM users WHERE user_name = ? ');
$sth->execute(array($user->friend));
//Works but then everything else not work
//return json_encode($sth->fetch());//NOT work
return json_encode($sth->fetchAll());
$count = $sth->rowCount();
if ($count == 1) {
// fetch one row (we only have one result)
$result = $sth->fetchAll();//NOT WORK
//$result = $sth->fetch();//NOT WORK
$ifexist = $this->db->prepare("SELECT friend_id FROM friends WHERE user_id = ? AND friend_id = ?");
$ifexist->execute(array($user->id, $result->user_id));
$count2 = $ifexist->rowCount();
if ($count2 == 1) {
//Friend already exist in friendslist
return false;
}else{
$token = $this->getToken(50);
$uid = $user->id;
$fid = $result->user_id;
$sth = $this->db->prepare('INSERT INTO friends
(user_id, friend_id, token)
VALUES (:user_id, :friend_id, :token)');
//we loop 2 times over the bindparams
//1st time with above settings ($uid & $fid) and 1 time with settings beneath
for($i = 1; $i <= 2; $i++ ) {
$sth->bindParam(':user_id', $uid);
$sth->bindParam(':friend_id', $fid);
$sth->bindParam(':token', $token);
$sth->execute();
//token stay the same
$token = $token;
//switch clients id($uid) as friends id
$uid = $result->user_id;
//switch friends id ($fid) as clients id
$fid = $user->id;
}
}
}
}
jQuery:在mvc View i中使用jquery从页脚附加数据:
function addFriend() {
$('#indicator').show();
//var checkFriendsName = $('#friendsName').val();
//alert(checkFriendsName);
var User = new Object();
User.id = uiD;
User.friend = $('#friendsName').val();
var userJson = JSON.stringify(User);
$.post(BaseUrl+"chat/run",
{
action: 'insert_friend',
user: userJson
},
function(data, textStatus) {
renderaddFriend(data);
$('#indicator').hide();
},
'json'
)
}
function renderaddFriend(jsonData) {
var checkInputName = $('#friendsName').val();
if (jsonData.length == 0) {alert(checkInputName+' not found') }//not work
$.each( jsonData, function( index, user){
alert(user.user_id);
});
}
我怎么还能将json_encode返回传递给jquery renderaddFriend函数?
答案 0 :(得分:1)
如果您只有一个结果行,->fetchAll()
将无法获取任何其他记录。
考虑将代码重写为:
$results = $sth->fetchAll();
if (count($results) == 1) {
$result = $results[0];
// do stuff
}
return json_encode($results);