Php function missing one record - php

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)){

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?

Output through json_encode using PDO in 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");

mysqli_num_rows generates unlimited amount of data

so, I'll try to explain it as good as I can with my knowledge in english.
I am trying to count data from my database, basically - how many fields I have with the same ID. here's image from database.
image from database
for example, in posts i have review system and it works, i have this PHP code to count how many same fields i have with review and id.
Here's the code:
<?php
$revposid = $res['content_id'];
$pos="SELECT review FROM comments WHERE review='positive' and postid=$revposid";
$neg="SELECT review FROM comments WHERE review='negative' and postid=$revposid";
$neu="SELECT review FROM comments WHERE review='neutral' and postid=$revposid";
if ($result=mysqli_query($_db,$pos)){$rowcountpos=mysqli_num_rows($result);}
if ($result=mysqli_query($_db,$neg)){$rowcountneg=mysqli_num_rows($result);}
if ($result=mysqli_query($_db,$neu)){$rowcountneu=mysqli_num_rows($result);}
?>
<div class="reviews" id="reviews">
<span class="good"><b class="fa fa-thumbs-up"></b><?php echo $rowcountpos ?></span>
<span class="neutral"><b class="icon-thumbs-up"></b><?php echo $rowcountneu ?></span>
<span class="bad"><b class="fa fa-thumbs-down"></b><?php echo $rowcountneg ?></span>
</div>
and when I try to use the same code
$revposid = $cont['content_id'];
$pos="SELECT content_id FROM user_content_like WHERE content_id=$revposid";
if ($result=mysqli_query($_db,$pos)){$rowcountpos=mysqli_num_rows($result);}
in my other script I have like system, it should show all my likes and under likes total likes of the post but when I use it it shows unlimited amount of data, i have no idea why. Here's the full code, I would appreciate some help or explanation.
<?php $ususername = $_GET['user_username'];$sql = "SELECT * FROM user_details WHERE user_username='$ususername'";$usresult = mysqli_query($_db,$sql);?>
<?php if( ! mysqli_num_rows($usresult) ) {
echo " Ooops? <br> <br>User <b>".$_GET["user_username"]."</b> doesn't exist.";
} else {
while($usrow = mysqli_fetch_array($usresult,MYSQLI_BOTH)) {?>
<?php
$current_user = $usrow['user_id'];
if ($_db->connect_error) {
die("Connection failed: " . $_db->connect_error);
}
$sql = "SELECT * FROM user_content_like WHERE user_id=$current_user ORDER BY date_added DESC;";
$result = $_db->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$content_id = $row['content_id'];
$sql1 = "SELECT * FROM content WHERE content_id=$content_id";
$result1 = $_db->query($sql1);
if ($_SESSION['user_id'] == $usrow['user_id']) {$output = '
<button type="button" class="unlike_button" onclick="unlike(this);" name="like_button" data-content_id="'.$row["content_id"].'" ><i class="fa fa-minus"></i></button>
';} else {
$output = '';
}
while($cont = $result1->fetch_assoc()) {
$revposid = $cont['content_id'];
$pos="SELECT content_id FROM user_content_like WHERE content_id=$revposid";
if ($result=mysqli_query($_db,$pos)){$rowcountpos=mysqli_num_rows($result);}
echo '
<div class="community-feed-thread">
<div class="community-icon-thread"></div>
<div class="community-comments-thread">'.$output.'</div>
<a href="'.$cont["content_id"].'" class="community-title-thread"><h3>'.$cont["title"].'</h3>
<span class="likes-desc"> Total likes: '.$rowcountpos.'</span>
</a>
</div>
';
}
}}
else {
echo " hmmmmmmmmmmmm.<Br><br>". $usrow["user_username"]." doesn't like anything. ";
}
$_db->close();
?>
<?php }}?>
this is how i want it to look
This is how it looks
Your re-using the same variable for different result sets in the code...
$result = $_db->query($sql);
and
if ($result=mysqli_query($_db,$pos))
You will need to ensure you only use the variable name once or it may have side effects in other loops.

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>';
}
?>

PHP - check if cell is empty

I'm writing a simple PHP page that is pulling information through into cards.
At the moment my script is hard coding the amount of "linktitle_1, linktitle_2, linktitle_3" etc that are able to be pulled through, at the moment it is 3, and if any of the 3 cells are empty they are still echoed out as empty, and with a comma afterwards.
What I want to do is to be able to print out any from 0-7 items of information. (The appropriate columns are present in the database)
Psuedo code would be something like this:
if (linktitle_1 = empty, linktitle_1_url = empty) {
echo '<p>linktitle_1</p>'}
else {
do nothing
};
I'm looking to do this with both the related links, and the link title sections. So I guess what I need to know is:
How do I escape the echo that these statements are to be inside of?
How do I use an if statement to check if something is empty/null?
Is there a more efficient way of doing this?
Code =
<?php
// DB details
$hostname = "localhost";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($hostname, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM relevant_topics";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Removing special characters from rows.
while($row = $result->fetch_assoc()) {
$title_clean = $row["title"];
$title_clean = strtolower($title_clean);
$title_clean = preg_replace('/\s*/ ', '', $title_clean);
$class_clean = $row["class"];
$class_clean = strtolower($class_clean);
$class_clean = preg_replace('/\s*/ ', '', $class_clean);
$related_clean_1 = $row["related1"] ;
$related_clean_1 = strtolower($related_clean_1);
$related_clean_1 = preg_replace('/[.,]\s*/ ', '', $related_clean_1);
$related_clean_2 = $row["related2"] ;
$related_clean_2 = strtolower($related_clean_2);
$related_clean_2 = preg_replace('/[.,]\s*/ ', '', $related_clean_2);
$related_clean_3 = $row["related3"] ;
$related_clean_3 = strtolower($related_clean_3);
$related_clean_3 = preg_replace('/[.,]\s*/ ', '', $related_clean_3);
$related_clean_4 = $row["related4"] ;
$related_clean_4 = strtolower($related_clean_4);
$related_clean_4 = preg_replace('/[.,]\s*/ ', '', $related_clean_4);
echo'
<div class="mix item '.$class_clean.'">
<h3>'.$row["title"].'</h3>
<p>'.$row["description"].'</p>
</br>
<p>Related Items:</p>
<p>
'.$row["related1"].'
'.$row["related2"].'
'.$row["related3"].'
'.$row["related4"].'
'.$row["related1"].',
'.$row["related2"].',
'.$row["related3"].', </p>
</br>
<div class="item-bottom '.$row["class"].'_counter">
See more
</div>
</div>
<div id="myModal'.$title_clean.'" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 class="modal-title modal-top-health">'.$row["title"].'</h3>
<br>
<p>'.$row["details"].'</p>
<br>
'.$row["linktitle_1"].',
<p>'.$row["linktitle_1_desc"].'</p>
'.$row["linktitle_2"].',
<p>'.$row["linktitle_2_desc"].'</p>
'.$row["linktitle_3"].',
<p>'.$row["linktitle_3_desc"].'</p>
</div>
</div>
</div>
</div>
';
}
} else {
echo "0 results";
}
$conn->close();
?>
Optimize with a loop, store the output in a variable:
// build list of titles
$titles = '';
for($i=1; $i<=7; ++$i) {
// check for data
if($row['linktitle_'.$i.'_url'] != null && $row['linktitle_'.$i] != null) {
// add to output
$titles .= '
'.$row['linktitle_'.$i].',
<p>'.$row['linktitle_'.$i.'_desc'].'</p>';
}
}
echo '
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 class="modal-title modal-top-health">'.$row["title"].'</h3>
<br>
<p>'.$row["details"].'</p>
<br>'.$titles.'
</div>';
You can then change that 7 to any number.
You can use htmlspecialchars() to escape the values if they might break the HTML.
$titles .= '
<a href="'.htmlspecialchars($row['linktitle_'.$i.'_url']).'">'.
htmlspecialchars($row['linktitle_'.$i]).', </a>
<p>'.htmlspecialchars($row['linktitle_'.$i.'_desc']).'</p>';
The same logic can be applied to the related links.
It could be optimized further at the database level by having a dedicated table for the titles:
table: relevant_topics_titles
topic_id | title_id | name | url | desc
Where topic_id is a foreign key to join with your table relevant_topics while title_id is a number between 1 and 7 (or less or more).
You could then fetch all the titles associated with your topic id and loop through them to build the list of titles.

Categories