Undefined index when using mysqli_fetch_all() - php

This snippet works only when I make a connection with PDO but I want it with mysqli.-->link
<?php
//fetch_comment.php
//$connect = new PDO('mysql:host=localhost;dbname=tbl_comment', 'root', '');
$connect = mysqli_connect('localhost','root','','tbl_comment');
$query = "
SELECT * FROM tbl_comment
WHERE parent_comment_id = '0'
ORDER BY comment_id DESC
";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$output = '';
//
foreach($result as $row)
{
$output .= '
<div class="panel panel-default">
<div class="panel-heading">By <b>'.$row["comment_sender_name"].'</b> on <i>'.$row["date"].'</i></div>
<div class="panel-body">'.$row["comment"].'</div>
<div class="panel-footer" align="right"><button type="button" class="btn btn-default reply" id="'.$row["comment_id"].'">Reply</button></div>
</div>
';
$output .= get_reply_comment($connect, $row["comment_id"]);
echo $output;
}
function get_reply_comment($connect, $parent_id = 0, $marginleft = 0)
{
$query = "
SELECT * FROM tbl_comment WHERE parent_comment_id = '".$parent_id."'
";
$output = '';
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$count = $statement->rowCount();
if($parent_id == 0)
{
$marginleft = 0;
}
else
{
$marginleft = $marginleft + 48;
}
if($count > 0)
{
foreach($result as $row)
{
.....
.....
...
?>
I tried to use mysqli fetch_all
$statement = $connect ->prepare("SELECT * FROM tbl_comment
WHERE parent_comment_id = '0'
ORDER BY comment_id DESC");
$statement->execute();
$resultSet = $statement->get_result();
$result = $resultSet->fetch_all();
$output = '';
.....
$statement = $connect ->prepare("
SELECT * FROM tbl_comment WHERE parent_comment_id = '".$parent_id."'
");
$statement->execute();
$resultSet = $statement->get_result();
$result = $resultSet->fetch_all();
$count = $statement->num_rows();
$output = '';
but I am getting this messages:
Notice: Undefined index: comment_sender_name in C:\xampp\htdocs\tbl_comment\fetch_comment.php on line 46
Notice: Undefined index: date in C:\xampp\htdocs\tbl_comment\fetch_comment.php on line 46
Notice: Undefined index: comment in C:\xampp\htdocs\tbl_comment\fetch_comment.php on line 47
Notice: Undefined index: comment_id in C:\xampp\htdocs\tbl_comment\fetch_comment.php on line 48
Notice: Undefined index: comment_id in C:\xampp\htdocs\tbl_comment\fetch_comment.php on line 51
Update: Thanks to #Dharman when I use the MYSQLI_ASSOC it displays me the comments(first MySQL statement) but not the replies (second MySql statement).It worked on PDO. I also have a file to write a comment but when I change from PDO to mysqli it writes it two times in the database:
<?php
//add_comment.php
//$connect = new PDO('mysql:host=localhost;dbname=tbl_comment', 'root', '');
$connect=mysqli_connect('localhost','root','','tbl_comment');
$error = '';
$comment_name = '';
$comment_content = '';
if(empty($_POST["comment_name"]))
{
$error .= '<p class="text-danger">Name is required</p>';
}
else
{
$comment_name = $_POST["comment_name"];
}
if(empty($_POST["comment_content"]))
{
$error .= '<p class="text-danger">Comment is required</p>';
}
else
{
$comment_content = $_POST["comment_content"];
}
if($error == '')
{
$query = "
INSERT INTO tbl_comment
(parent_comment_id, comment, comment_sender_name)
VALUES (:parent_comment_id, :comment, :comment_sender_name)
";
$statement = $connect->prepare($query);
$statement->execute(
array(
':parent_comment_id' => $_POST["comment_id"],
':comment' => $comment_content,
':comment_sender_name' => $comment_name
)
);
$error = '<label class="text-success">Comment Added</label>';
}
$data = array(
'error' => $error
);
echo json_encode($data);
?>

Just use $result = $resultSet->fetch_all(MYSQLI_ASSOC);
By default fetch_all returns numerical array, but you want an associative array. Pass the constant as an argument to fetch_all

Related

How can I use json response from php in jquery?

I'm trying to do a website. I need to get all the reviews in the database. My initial guess was to use php like this:
function get_all_reviews(){
$db = dbConnection();
$db -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = "SELECT Nome, Title, reviews.Review, users.Email FROM `users` JOIN `reviews` WHERE users.Email = reviews.Email; ";
$statement = $db -> prepare($query);
$statement->execute();
$result = $statement->fetchAll();
foreach ($result as $row) {
$name = $row["Nome"];
$title = $row["Title"];
$review = $row["Review"];
$email = $row["Email"];
?>
<div class="box" id="<?= $email ?>">
<div class="nome"><?= $name ?> dice:</div>
<div class="titolo"><?= $title ?> </div>
<div class="recensione"><?= $review ?> </div>
<button class="admin_bottom">X</button>
</div>
<?php
}
But since it's a project for the university, I need to not use it (it's mandatory). I need to send the request with jquery, then with php I should send the response with json, but I don't get how to recall the reviews and list them.
I try with this with php:
function gett_all_reviews(){
$db = dbConnection();
$db -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = "SELECT Nome, Title, reviews.Review, users.Email FROM `users` JOIN `reviews` WHERE users.Email = reviews.Email; ";
$statement = $db -> prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$resultSet = '{ ';
foreach ($result as $row) {
$resultSet .= '{"name": "'.$row["Nome"].'",';
$resultSet .= '"title": "'.$row["Title"].'",';
$resultSet .= '"review": "'.$row["Review"].'",';
$resultSet .= '"email": "'.$row["Email"].'"},';
}
$resultSet .= '}';
$db = null;
return $resultSet;
}
$s = get_all_reviews();
echo $s;
and with jquery:
$.getJSON( "../php/get_reviews.php", function( json ) {
for (let index = 0; index < json.length; index++) {
$("#conteiner_reviews").append(
"<div class=\"box\" id= \""+ json[index].email+ "\">"+
"<div class=\"nome\">"+json[index].name +" dice:</div>" +
"<div class=\"titolo\"><"+json[index].title+"</div>"+
"<div class=\"recensione\">"+json[index].review +"</div></div>");
}
});
But doesn't work.
function gett_all_reviews(){
$db = dbConnection();
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = "SELECT Nome as name, Title as title, reviews.Review as review, users.Email as email FROM `users` JOIN `reviews` WHERE users.Email = reviews.Email; ";
$statement = $db -> prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$db = null;
return $result;
}
echo json_encode(get_all_reviews());
$.getJSON('../php/get_reviews.php', function (data) {
$.each(data, function (item) {
$('#conteiner_reviews').append(
'<div class="box" id="' + item.email+ '">' +
'<div class="nome">' + item.name + 'dice:</div>' +
'<div class="titolo">' + item.title + '</div>' +
'<div class="recensione">' + item.review + '</div>'
);
});
});

Can't PDO with multiple select LIKE

Having trouble with the following code. It's not giving an error nor does it output anything. The problem is with the multipleReg part. If I remove bindValue multiplereg and replace :multiplereg in the select statement with $multipleReg it works. I have a feeling it's cause it's not an array but I've tried executing it as an array which has not worked. Any help would be much appreciated.
<?php
header('Content-Type: application/json; Charset=UTF-8');
require "includes/config.php";
$offset = $_GET["offset"];
$region = trim($_GET["region"]);
$regionExp = explode(",", $region);
$tag = $_GET["tag"];
$data = array();
foreach ($regionExp as $singleReg)
$queryKeyword[] = "'%$singleReg%'";
$multipleReg = implode(' OR region LIKE ', $queryKeyword);
try {
$sql = "SELECT * FROM news WHERE FIND_IN_SET(`tag`, :tag) AND
(region LIKE :multipleReg) ORDER BY id DESC LIMIT 10 OFFSET :offsetNr";
$stmt = $db->prepare($sql);
$stmt->bindValue(':tag', $tag);
$stmt->bindValue(':multipleReg', $multipleReg);
$stmt->bindValue(':offsetNr', (int) $offset, PDO::PARAM_INT);
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$data[] = $row;
}
echo json_encode($data);
$stmt->closeCursor();
exit();
} catch(PDOException $e) {
echo $e->getMessage();
}
?>
You could create an array to prepare your SQL string and another to store placeholders :
$qstr = [];
foreach ($regionExp as $k => $singleReg) {
$queryKeyword[':lk'.$k] = "%$singleReg%";
$qstr[] = 'region LIKE :lk'.$k ;
}
Then your SQL query (don't forget to check if $qstr is not empty) :
$sql = "SELECT * FROM news WHERE FIND_IN_SET(`tag`, :tag)
AND (".implode(' OR ', $qstr).")
ORDER BY id DESC LIMIT 10 OFFSET :offsetNr";
And to bind :
// Instead of : $stmt->bindValue(':multipleReg', $multipleReg);
foreach ($queryKeyword as $k => $v) $stmt->bindValue($k, $v);
EDIT The full code :
$offset = $_GET["offset"];
$region = trim($_GET["region"]);
$regionExp = explode(",", $region);
$tag = $_GET["tag"];
// This part has changed :
$qstr = [];
foreach ($regionExp as $k => $singleReg) {
$queryKeyword[':lk'.$k] = "%$singleReg%";
$qstr[] = 'region LIKE :lk'.$k ;
}
try {
// The SQL string changed
$sql = "SELECT * FROM news WHERE FIND_IN_SET(`tag`, :tag)
AND (".implode(' OR ', $qstr).")
ORDER BY id DESC LIMIT 10 OFFSET :offsetNr";
// Debug (see below)
// echo $sql."\n" ;
// print_r($queryKeyword);
$stmt = $db->prepare($sql);
$stmt->bindValue(':tag', $tag);
// The line below replaced
foreach ($queryKeyword as $k => $v) $stmt->bindValue($k, $v);
$stmt->bindValue(':offsetNr', (int) $offset, PDO::PARAM_INT);
$stmt->execute();
$data = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$data[] = $row;
}
echo json_encode($data);
$stmt->closeCursor();
exit();
} catch(PDOException $e) {
echo $e->getMessage();
}
The SQL and dump will look like this :
SELECT * FROM news WHERE FIND_IN_SET(`tag`, :tag)
AND (region LIKE :lk0 OR region LIKE :lk1)
ORDER BY id DESC LIMIT 10 OFFSET :offsetNr
Array
(
[:lk0] => %test%
[:lk1] => %test2%
)

Why is this piece of code giving me duplicate results?

This is probably really easy and I'm probably gonna kick myself up the arse after this, but I have the following code which displays either html or json of data from a table and returns it.
<?php
session_start();
$base = dirname(dirname(__FILE__));
include($base."/include/db.php");
global $conn;
$trees = [];
$treeBoxes = [];
if(isset($_SESSION['clientId'])) {
$clientId = $_SESSION['clientId'];
$query = $conn->prepare("SELECT * FROM ct_trees WHERE client_id=?");
$query->bind_param('i', $clientId);
$query->execute();
$result = $query->get_result();
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$tree_id = $row['id'];
$tree_name = $row['name'];
$query = $conn->prepare("SELECT id FROM ct_connections WHERE tree_id=?");
$query->bind_param('i', $tree_id);
$query->execute();
$result2 = $query->get_result();
$connections = $result2->num_rows;
array_push($treeBoxes, '<span class="checkbox abc-checkbox abc-checkbox-success">',
'<input id="tree'.$tree_id.'" type="checkbox" rel="'.$tree_id.'">',
'<label for="tree'.$tree_id.'">'.$tree_name.'</label>',
'</span>');
array_push($trees, ["id" => $tree_id, "name" => $tree_name, "connections" => $connections]);
if(isset($_GET['json'])) {
echo json_encode($trees);
} else {
echo join("", $treeBoxes);
}
}
}
}
?>
Now let's say for example, we want the json result, I'm getting the following string:
[{"id":1,"name":"My Tree","connections":4360}][{"id":1,"name":"My Tree","connections":4360},{"id":4,"name":"Another Tree","connections":0}]
Now for some reason, it's giving me the first result in one array, and then the same result, but with the other rows, in a separate array.
Fixed it, I knew it'd be silly:
<?php
session_start();
$base = dirname(dirname(__FILE__));
include($base."/include/db.php");
global $conn;
$trees = [];
$treeBoxes = [];
if(isset($_SESSION['clientId'])) {
$clientId = $_SESSION['clientId'];
$query = $conn->prepare("SELECT * FROM ct_trees WHERE client_id=?");
$query->bind_param('i', $clientId);
$query->execute();
$result = $query->get_result();
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$tree_id = $row['id'];
$tree_name = $row['name'];
$query = $conn->prepare("SELECT id FROM ct_connections WHERE tree_id=?");
$query->bind_param('i', $tree_id);
$query->execute();
$result2 = $query->get_result();
$connections = $result2->num_rows;
array_push($treeBoxes, '<span class="checkbox abc-checkbox abc-checkbox-success">',
'<input id="tree'.$tree_id.'" type="checkbox" rel="'.$tree_id.'">',
'<label for="tree'.$tree_id.'">'.$tree_name.'</label>',
'</span>');
array_push($trees, ["id" => $tree_id, "name" => $tree_name, "connections" => $connections]);
}
//Moved echo outside of while loop.
if(isset($_GET['json'])) {
echo json_encode($trees);
} else {
echo join("", $treeBoxes);
}
}
}
?>

MySQL-Link Error in php function

i am beginner in php . and i have this Sql problem:
function InsertUserBirdsFromFile($File_content){
for($i =0; $i < count($File_content); $i+=2){
$id = $this->Master_file($File_content[$i], $File_content[$i + 1] );
if(isset($id)){
try{
$qry = "insert into user_to_birds(user_id,tax_id)values( 1 ,'.$id .') ";
$result = mysql_query($qry,$this->connection);
}
catch(Exception $ex){ echo $ex;}
}
}
}
function Master_file($name, $latin ){
try{
$qry = "SELECT tax_id FROM master where name =".$name." and latin =".$latin;
$result = mysql_query($qry,$this->connection);
}
catch(Exception $ex){ return null;}
if ($result == true && mysql_num_rows($result) >0) {
$p=0;
while ($Res_user = mysql_fetch_array($result) ) {
$marques[$p] = $Res_user;
$p++;
}
return $marques[0]['tax_id'];
}
else return null;
}
the error shown is : Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource in /home/admin/public_html/hitlist/include/fg_membersite.php on line 427
in this line $result = mysql_query($qry,$this->connection);.
what is the problem? How can i fix it?
Well, maybe unrelated but i think this needs to be fixed
$qry = "insert into user_to_birds(user_id,tax_id)values( 1 ,'.$id .') "
to
$qry = "insert into user_to_birds(user_id,tax_id)values( 1 ,".$id .") "
or
$qry = "insert into user_to_birds(user_id,tax_id)values( 1 ,$id) "

Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\glasanje\index.php on line 111

<?php
foreach (iscupaj_viceve() as $id => $glasanje){
$result = mysql_query("SELECT * FROM vicevi WHERE id = $id");
while ($row = mysql_fetch_array($query)) {
echo "<h2><center>".$row['Title']."</h2>";
echo "<div id='linkovi1'>" .nl2br($row["VicText"]). "<br></div>";
}
?>
<p>
<img src="../images/plus_sign.png" width="29" height="29">
<img src="../images/minus_sign.png" width="29" height="29">
Ukupno glasova : [
<?php
include 'core/db/connect.php';
// Check connection
$result = mysql_query("SELECT glasanje FROM vicevi WHERE id = $id");
while($row = mysql_fetch_array($result))
{
echo nl2br($row['glasanje']);
}
?>]
</p>
<?php
}
?>
And this is my function
function iscupaj_viceve(){
$sql = "SELECT id, VicText, glasanje FROM vicevi ORDER BY id DESC LIMIT 0, 10";
$rezultati = mysql_query($sql);
$glasanje = array();
while (($row = mysql_fetch_assoc($rezultati)) !== false){
$rezultati[$row['id']] = $row['VicText'];
}
return $rezultati;
}
Browser prints this error message:
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\glasanje\index.php on line 111
But i can't seem to find a way to solve this problem :S Help?
Your function is overwriting $rezultati. I would suggest rewriting it as:
function iscupaj_viceve() {
$rows = array();
$sql = "SELECT id, VicText, glasanje FROM vicevi ORDER BY id DESC LIMIT 0, 10";
$rezultati = mysql_query($sql);
while (($row = mysql_fetch_assoc($rezultati)) !== false) {
$rows[$row['id']] = $row['VicText'];
}
return $rows;
}
iscupaj_viceve() doesn't always return an array.
$glasanje = array();
should be
$rezultati = array();

Categories