Output through json_encode using PDO in php - php

I have being trying to output data from database using the below code but finding difficult displaying the fetched data on screen. Using PDO in php to trigger the selection. What should I do to resolve this issue?
<?php
include ("core.php");
$output = array('data' => array());
$sql = "SELECT categories_id, categories_name, categories_active, categories_status FROM categories WHERE categories_status = ?";
$result = $connect->prepare($sql);
$result->execute([1]);
if($result->rowCount() > 0) {
// $row = $result->fetch_array();
$activeCategories = "";
while($row = $result->fetchAll()) {
$categoriesId = $row[0];
// active
if($row[2] == 1) {
// activate member
$activeCategories = "<label class='label label-success'>Available</label>";
} else {
// deactivate member
$activeCategories = "<label class='label label-danger'>Not Available</label>";
}
$button = '<!-- Single button -->
<div class="btn-group">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Action <span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li><a type="button" data-toggle="modal" id="editCategoriesModalBtn" data-target="#editCategoriesModal" onclick="editCategories('.$categoriesId.')"> <i class="glyphicon glyphicon-edit"></i> Edit</a></li>
<li><a type="button" data-toggle="modal" data-target="#removeCategoriesModal" id="removeCategoriesModalBtn" onclick="removeCategories('.$categoriesId.')"> <i class="glyphicon glyphicon-remove-sign"></i> Remove</a></li>
<li><a type="button" data-toggle="modal" data-target="#deleteCategoriesModal" id="deleteCategoriesModalBtn" onclick="deleteCategories('.$categoriesId.')"> <i class="glyphicon glyphicon-trash"></i> Delete</a></li>
</ul>
</div>';
$output['data'][] = array(
$row[1],
$activeCategories,
$button
);
} // /while
}// if num_rows
$connect = null;
echo json_encode($output);
?>
Please I below is the html code which accept the output. Please I'm just a beginner. Kindly help me.
<thead>
<tr>
<th>Categories Name</th>
<th>Status</th>
<th style="width:15%;">Options</th>
</tr>
</thead>
</table>```

The fetchAll() function will get you all the rows and columns, not just one. With that said, just get the variable $row outside of the while loop, call it differently (let's say, $rows), and then iterate over the loop using something like foreach ($rows as $row). Also, now your $row will not take numerical indices, but rather indices with the names of what you selected in the SQL query, like $row['categories_id'].
This should sort out iterating over the rows that you got. One more thing I'm not sure about is $result->execute([1]);, as that function takes parameters, and you're only giving it a 1-element array with the number 1, although I really can't tell because I don't have the rest of the code. My guess is that you're trying to use JavaScript with AJAX, as you're printing the encoded $output variable, so you'll need to get the input at the very beginning using php://input, where you'll get all the parameters that are sent by AJAX, and, before encoding, set the content type to application/json using the function header("Content-type: application/json");

Related

php foreach button issue

What I exactly need:
inside the foreach for every element I create a button. Then connect to postgresql db, select data from the table by condition.
If there is a matching entry in the database then I display <span class="fa fa-heart"> </span>. If no entries then display <span class="far fa-heart"></span>. I need this output exactly inside <button> </button> tag.
<form method="POST">
<?php foreach ($rows as $data): ?>
<button class="btn btn-outline-danger mx-1" name=fav-click style="font-size: 11px;">
<?php
$linkk = pg_connect("host=localhost dbname=webportal user=postgres password=1234567");
$favor=(int)$data['obj_id'];
$id_usr=(int)$id;
$query = "select obj_id, usr_id from favorites where usr_id='$id_usr' and obj_id='$favor'";
$re = pg_query($linkk, $query);
$row1=pg_fetch_all($re);
if(pg_num_rows($re)==0)
{
echo '<span class="far fa-heart"></span>';
}
if(pg_num_rows($re)>0)
{
echo '<span class="fa fa-heart"> </span>';
}
?>
</button>
inside the form there also are
<input type=hidden name=obj_id value=<?= $data['obj_id'];?>>
<input type=hidden name=id_usr value=<?= $id; ?>>
in which I store the values ​​I need.
Outside the foreach I have:
<?php
if(isset($_POST['fav-click']) && isset($_POST['obj_id']) && isset($_POST['id_usr'])) {
$oo = $_POST['obj_id'];
$uu=$_POST['id_usr'];
if(pg_num_rows($re)==0)
{
$zapr="insert into favorites(obj_id, usr_id) values($oo, $uu)";
$done = pg_query($linkk, $zapr);
}
if(pg_num_rows($re)>0)
{
$zapr="delete from favorites where obj_id='$oo' and usr_id='$uu'";
$done = pg_query($linkk, $zapr);
}
}
?>
But it works not correctly because it always displays and does queries in the db for the last element of foreach. Doesn't matter if I click a button for another one.
How can I fix it?

how can I edit/remove info in MySQL database via bootstrap table

I'm creating an admin panel for small ecommerce website (to practice) and I have no idea how to make php understand which id product I want to update after I click this little <i></i> element because I already use $_POST['<i> element name'] in order to detect whether or not it's ready to be updated, I know you cannot assign 2 names to one element otherwise I could use $id = $results['id']; as second name... any advices? I'm completely new in php. sorry if this post is stupid I just need some help...
$query="select * FROM productadd";
$result= mysqli_query($connection, $query);
$results = mysqli_fetch_array($result);
if(!empty($results['id'])) {
while($results = mysqli_fetch_array($result)){
$id = $results['id'];
$name = $results['name'];
$text = $results['text'];
$price = $results['price'];
$image = $results['image'];
echo '
<tr>
<td>'.$id.'</td>
<td>'.$name.'</td>
<td>'.$text.'</td>
<td>$'.$price.'</td>
<td>
<img src="'.$image.'" style="style="display:block;" width="100%" height="100%" ">
</td>
<td>
<a class="add" value="asd" title="Add" name="edit" data-toggle="tooltip">
<i class="material-icons"></i>
</a>
<a class="edit" name="edit" title="Edit" data-toggle="tooltip">
<i class="material-icons"></i>
</a>
<a class="delete" title="Delete" data-toggle="tooltip">
<i class="material-icons"></i>
</a>
</td>
</tr>';
}
}

Change Enum With OOP PHP

I'm new to learning web development with PHP and I have a problem I'm trying to solve. I have an ENUM type in my database which is of 2 values: "Y" or "N". It is called userStatus inside my user table (tbl_users). I'm trying to use PHP to change that ENUM value for that particular user when a button is clicked. However when I click the button nothing happens and I'm unsure if its the button or my PHP or a combination of both being wrong which is causing this not to work?
PHP to change ENUM:
if(isset($_POST['btn-activate'])){
if(isset($_GET['id']))
{
$id = $_GET['id'];
extract($user_home->getID($userId));
$statusY = "Y";
$statusN = "N";
$stmt = $user->runQuery("SELECT userID,userStatus FROM tbl_users WHERE userID=:uID");
$stmt->execute(array(":userID"=>$userId));
$row=$stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() > 0)
{
if($row['userStatus']==$statusN)
{
$stmt = $user->runQuery("UPDATE tbl_users SET userStatus=:status WHERE userId=:userID");
$stmt->bindparam(":status",$statusY);
$stmt->bindparam(":userID",$userId);
$stmt->execute();
$msg = "
<div class='alert alert-success'>
<button class='close' data-dismiss='alert'>×</button>
<strong>WoW !</strong> Your Account is Now Activated : <a href='manage_users.php'></a>
</div>
";
}
else
{
$msg = "
<div class='alert alert-error'>
<button class='close' data-dismiss='alert'>×</button>
<strong>sorry !</strong> Your Account is allready Activated : <a href='manage_users.php'></a>
</div>
";
}
}
else
{
$msg = "
<div class='alert alert-error'>
<button class='close' data-dismiss='alert'>×</button>
<strong>sorry !</strong> No Account Found : <a href='manage_users.php'></a>
</div>
";
}
}
}
Get user id function:
public function getID($userId)
{
$stmt = $this->db->prepare("SELECT * FROM tbl_users WHERE userId=:id");
$stmt->execute(array(":id"=>$userId));
$editRow=$stmt->fetch(PDO::FETCH_ASSOC);
return $editRow;
}
Table Which displays users:
$database = new Database();
$db = $database->dbConnection();
$conn = $db;
$query = "SELECT * FROM tbl_users";
$stmt = $conn->prepare($query);
$stmt->execute();
while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
?>
<tr>
<td><?php echo $row['userID']?></td>
<td><?php echo $row['userName']?></td>
<td><?php echo $row['userFirstName']." ".$row['userSurname']; ?></td>
<td><?php echo $row['userEmail']?></td>
<td><?php echo $row['userRole']?></td>
<td><?php echo $row['userStatus']?></td>
<td>
And My button at the end of the table which should, when clicked, run the PHP at the to:
<?php if($row['userStatus'] == ('N')){
echo ' <button type="submit" class="btn btn-info"><i class="glyphicon glyphicon-ok" name="btn-activate" ></i> Activate</button>';
}else{
echo ' <button class="btn btn-default"><i class="glyphicon glyphicon-eye-close"></i> Archive</button>';
} ?>
<button data-toggle="modal" data-target="#view-modal" data-id="<?php echo $row['userID']; ?>" id="getUser" class="btn btn-warning"><i class="glyphicon glyphicon-pencil"></i> Edit</button>
</td>
</tr>
Thanks in advance.
There is no code (nothing happens) if either of the first two if conditions don't evaluate to TRUE.
Consider adding some debugging output. At least add an else for each of those ifs and echo some debug output.
Very strange that the code is checking both $_POST and $_GET. I suspect that id is being passed in on the form submit, just like btn-activate, and not as a parameter in the uri. (i.e. Did you mean $_POST['id'] ? Just guessing here.
We see a reference to $userid in this line:
extract($user_home->getID($userId));
But we don't see what value is assigned to $userId. The preceding line attempts to set a variable named $id. But we don't see $id being used anywhere else.
Personally, I'd avoid using the extract function where it isn't specifically needed. (I don't want my code susceptible to malfunctioning, in this example, when someone adds a column to tbl_users.)
http://ericlippert.com/2014/03/05/how-to-debug-small-programs/
Put the name attribute to your button, not in the <i> element.
<?php
if($row['userStatus'] == ('N')){
echo ' <button type="submit" class="btn btn-info" name="btn-activate"><i class="glyphicon glyphicon-ok"></i> Activate</button>';
} else {
echo ' <button class="btn btn-default"><i class="glyphicon glyphicon-eye-close"></i> Archive</button>';
}
?>

How do you pass a A HREF value from a php function?

So with this code we pull in some data from a mysql database with php. Then everything works, except the a href formatting (for bootstrap). This code is really long, so I tried to get the parts that pertain to the problem.
The drop down works great when it isn't part of this function and all the data pulls through like it should. The function somehow throws out the bootstrap class, id, role, etc. in a href.
function menu_element_builder($values) {
$links = '';
foreach($values as $value) {
if(is_array($value['args'])) {
$links .= (!empty($value['href']))?'
/* this a href part doesn't pull through the ID, Role, data-toggle, or class */
<a id="dLabel" role="button" data-toggle="dropdown" class="btn btn-primary" href="'.$value['href'].'">'.$value['name'].'<span class="caret"></span>
</a>
<ul class="dropdown-menu multi-level" role="menu" aria-labelledby="dropdownMenu">':'
<li class="dropdown-submenu">
'.$value['name'].'
</li> //it has more than this, keeping it simple
</ul>
return $links;
}
(an array of $link values are listed)
//This is part of case break statements to know which icons to load
$themed_elements = menu_element_builder($link_values);
<html>
<body>
<div class="dropdown">
<?php echo $themed_elements; ?>
</div>
</body>
</html>
old code
function menu_element_builder($values) {
$links = '';
foreach($values as $value) {
if(is_array($value['args'])) {
$links .= (!empty($value['href']))?'<li><a class="dir" href="'.$value['href'].'">'.$value['name'].'</a><ul>':'<li><span class="dir">'.$value['name'].'</span></li></ul>';
<script type="text/javascript">
$(function(){
$(".dir").click(function(){
//this.addclass('ul.dropdown li:hover');
});
});

Php function missing one record

I have a php function
function getMembersByFamilyNumber($familyNumber){
$html = "";
$query = db_execute("SELECT * FROM `family_members` WHERE `family_number` = '".$familyNumber."' and `isActive`= '1' and `isDelete`= '0' ORDER BY id DESC");
$check = mysql_fetch_assoc($query);
if ($check) {
while($result = mysql_fetch_assoc($query)){
extract($result);
$html.='
<li>
<time class="cbp_tmtime" datetime="2013-04-10 18:30"><span>'.$familyNumber.'</span> <span>'.$relation_head.'</span></time>
<div class="cbp_tmicon cbp_tmicon-phone"></div>
<div class="cbp_tmlabel">
<h2>'.$name.'</h2>
<button type="button" class="btn btn-success pull-right" onclick="editPageContent(\'editpagecontent\',\'editMember\',\''.$id.'\');">Edit</button>
<button type="button" class="btn btn-danger pull-right" onclick="deletePageContent(\'deletepagecontent\',\'deleteHead\',\''.$id.'\');">Delete</button>
<ul>
<li>Age: '.$age.' years old</li>
<li>Education: '.$education.'</li>
<li>Occupation: '.$occupation.'</li>
<li>Alive: '.$alive.'</li>
<li>Phone: '.$phone.'</li>
<li>CNIC: '.$cnic.'</li>
</ul>
</div>
</li>
';
}
return $html;
exit;
}else{
return "<li><h2>No members found.</h2></li>";
}
}
Is is returning only one record, but in database there is two records against this query, whenever i i execute this query in MySQL it returning two rows, but whenever i run this code it return only second record, missing first record, every time it missing first record. means if my table have 5 records this function returns 4 records and miss 1st record. Why this happens? help me.
Use mysql_num_rows($query) not use
$check = mysql_fetch_assoc($query);
if ($check) {
This is correct solution:
if (mysql_num_rows($query) > 0) {
while($result = mysql_fetch_assoc($query)){

Categories