Server Side Ajax JQuery CRUD DataTable - PHP PDO, MySql - php

I am trying to fetch data from child table using Id stored in the child table to populate DataTable and display records related to Parent table and child table. Below is the code:
Problem is when I add WHERE statement to fetch records based on HolderID shows number of entries returned but not displayed. And filtered also shows 0
Code:
function get_beneficaries_records($rowId)
{
include('db.php');
$statement = $connection->prepare("SELECT * FROM beneficiaries WHERE HolderID = $rowId");
$statement->execute();
$result = $statement->fetchAll();
return $statement->rowCount();
}
Fetching records on fectchrecords.php.
$query .= "SELECT * FROM pro_beneficiaries";
if(isset($_POST["search"]["value"]))
{
$query .= ' WHERE BeneficiaryIDNo LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= 'OR LastName LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= 'OR Initials LIKE "%'.$_POST["search"]["value"].'%" ';
}
if(isset($_POST["search"]["value"]))
{
$query .= 'OR BeneficiaryIDNo LIKE "%'.$_POST["search"]["value"].'%" ';
}
if(isset($_POST["order"]))
{
$query .= 'WHERE FK_HolderID = $rowIds';
$query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
}
else
{
$query .= 'ORDER BY BID DESC ';
}
if($_POST["length"] != -1)
{
$query .= ' WHERE BeneficiaryID LIKE "%'.$_POST["search"]["value"].'%" ';
}
$statement = $connection->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$data = array();
$filtered_rows = $statement->rowCount();
foreach($result as $row)
{
$sub_array = array();
$sub_array[] = $row["Initials"];
$sub_array[] = $row["LastName"];
$sub_array[] = $row["BeneficiaryIDNo"];
$sub_array[] = $row["Relationship"];
$sub_array[] = $row["MemberType"];
$sub_array[] = '<button type="button" name="update" id="'.$row["BID"].'" class="btn btn-outline-warning btn-xs updatebeneficiary"><i class="fa fa-pencil-alt"></i></button>';
$sub_array[] = '<button type="button" name="delete" id="'.$row["BID"].'" class="btn btn-outline-danger btn-xs deletebeneficiary"><i class="fa fa-minus"></i></button>';
$data[] = $sub_array;
}
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => $filtered_rows,
"recordsFiltered" => get_beneficaries_records($rowId),
"data" => $data
);
echo json_encode($output);

I would print raw content of the query result, I would print the query itself so I see what the code produced, then I could run it in a separate client (I love HeidiSQL for this).
And I think there might a condition where it will put duplicate WHERE
if(isset($_POST["order"]))
{
$query .= 'WHERE FK_HolderID = $rowIds';
}
if($_POST["length"] != -1)
{
$query .= ' WHERE BeneficiaryID LIKE "%'.$_POST["search"]["value"].'%" ';
}
I would form it into one WHERE and use boolean AND OR to form the conditions I want

Related

PHP JSON from mysql database not showing any result

I have a problem getting the data in JSON format via the data.php file.
When I try see JSON I got this:
"{"draw":0,"recordsTotal":null,"recordsFiltered":120,"data":[]}"
but needs the php script to retrieve data from the table all entries for the column date, name, id like datatables AJAX instructions . When doing this using the local XAMPP server, the script retrieves the entries from the mysql table and the data is displayed as a table using datatables.
Here is my PHP code
$connect = new PDO("mysql:host=localhost;dbname=abc", "root", "PASSWORD");
$query = "SELECT * FROM abc_result ";
if(isset($_POST["search"]["value"]))
{
$query .= '
WHERE DATE LIKE "%'.$_POST["search"]["value"].'%"
OR NAME LIKE "%'.$_POST["search"]["value"].'%"
OR ID LIKE "%'.$_POST["search"]["value"].'%"
';
}
if(isset($_POST['DATE']))
{
$query .= 'ORDER BY '.$column[$_POST['DATE']['0']['column']].' '.$_POST['DATE']['0']['dir'].' ';
}
else
{
$query .= 'ORDER BY ID DESC ';
}
$query1 = '';
if($_POST['length'] != -1)
{
$query1 = 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$statement = $connect->prepare($query);
$statement->execute();
$number_filter_row = $statement->rowCount();
$result = $connect->query($query . $query1);
$data = array();
foreach($result as $row)
{
$sub_array = array();
$sub_array[] = $row['DATE'];
$sub_array[] = $row['NAME'];
$sub_array[] = $row['ID'];
$data[] = $sub_array;
}
function count_all_data($connect)
{
$query = "SELECT COUNT(*) FROM abc_result";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchColumn();
return $result;
}
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => count_all_data($connect),
"recordsFiltered" => $number_filter_row,
"data" => $data
);
echo json_encode($output);
I'm trying to retrieve data from my mysql database and display it using datatables. locally I've been able to do it but I'd like to do it on a NAS (QNAP) so that when I go to a website the table would be visible by anyone who visits it. To do this, I installed MariaDB 5 and PHPmyAdmin. I was able to connect to the database but the php code does not display the data as I would like it to

How to properly display a specific records with datatable using PHP

I am working with datatable and the code can successfully display the entire records. searching of records is also working.
I am trying to display a specific record when page loads. you can see that SELECT * FROM users will display all records at once. I need to display a specific record when page loads like SELECT * FROM users where id=$userid and email=$email.
In normal PDO query I can just do
$result = $db->prepare("SELECT * FROM users where email=:email and id=:id");
$result->execute(array(':email' => $email,':id' => $userid));
Here in the datatable is a little bit complicated.
Where do I add something like
$sql .= 'WHERE id = '.$userid.' and email = '.$email.' ';
Here is the full code for datatable backend:
<?php
include('db.php');
if(isset($_POST["get_content"])){
$get_content = strip_tags($_POST["get_content"]);
if($get_content == 'get_data'){
$userid =102;
$email = 'test#gmail.com';
$sql= '';
$error = '';
$message='';
$response= array();
$sql .= "SELECT * FROM users ";
if(isset($_POST["search"]["value"])){
$value= $_POST["search"]["value"];
$sql.= 'WHERE fullname LIKE "%'.$value.'%" ';
$sql .= 'OR email LIKE "%'.$value.'%" ';
}
$start = $_POST['start'];
$length = $_POST['length'];
$draw= $_POST["draw"];
if(isset($_POST["order"])){
$order_column = $_POST['order']['0']['column'];
$order_dir = $_POST['order']['0']['dir'];
//$sql .= 'WHERE id '.$userid.' ';
$sql .= 'ORDER BY '.$order_column.' '.$order_dir.' ';
}
else{
$sql.= 'ORDER BY id DESC ';
}
if($length != -1){
$sql .= 'LIMIT ' . $start . ', ' . $length;
}
$pstmt = $db->prepare($sql);
$pstmt->execute();
$rows_count = $pstmt->rowCount();
while($row = $pstmt->fetch()){
$rows = array();
$rows[] = $row['id'];
$rows[] = $row['fullname'];
$rows[] = $row['email'];
$response[] = $rows;
}
$data = array(
"draw" => $draw,
"recordsTotal" => $rows_count,
"data" => $response);
}
echo json_encode($data);
}
?>
As per my understanding, you need manage to put WHERE condition for id, email in your example code,
Do change some portion of your code:
$sql .= "SELECT * FROM users ";
// ADD YOUR REQUIREMENT CONDITION
$sql .= 'WHERE id = '.$userid.' and email = '.$email.' ';
if (isset($_POST["search"]["value"])){
$value = $_POST["search"]["value"];
// CHANGED WHERE TO AND
$sql .= 'AND (fullname LIKE "%'.$value.'%" ';
$sql .= 'OR email LIKE "%'.$value.'%") ';
}

PHP CRUD operations with search, and operator

I am using below function ( i got this from internet) to fetch data from DB and its working fine. If i use where and search condition is not working properly or i have missed some thing. Can any one help me to fix this issue.
public function getRows($table,$conditions = array()){
$sql = 'SELECT ';
$sql .= array_key_exists("select",$conditions)?$conditions['select']:'*';
$sql .= ' FROM '.$table;
if(array_key_exists("where",$conditions)){
$sql .= ' WHERE ';
$i = 0;
foreach($conditions['where'] as $key => $value){
$pre = ($i > 0)?' AND ':'';
echo $sql .= $pre.$key." = '".$value."'";
$i++;
}
}
if(array_key_exists("search",$conditions)){
$sql .= (strpos($sql, 'WHERE') !== false)?'':' WHERE ';
$i = 0;
foreach($conditions['search'] as $key => $value){
$pre = ($i > 0)?' OR ':'';
$sql .= $pre.$key." = '".$value."'";
$i++;
}
}
if(array_key_exists("order_by",$conditions)){
$sql .= ' ORDER BY '.$conditions['order_by'];
}
if(array_key_exists("start",$conditions) && array_key_exists("limit",$conditions)){
$sql .= ' LIMIT '.$conditions['start'].','.$conditions['limit'];
}elseif(!array_key_exists("start",$conditions) && array_key_exists("limit",$conditions)){
echo $sql .= ' LIMIT '.$conditions['limit'];
}
$query = $this->conn->prepare($sql);
$query->execute();
if(array_key_exists("return_type",$conditions) && $conditions['return_type'] != 'all'){
switch($conditions['return_type']){
case 'count':
$data = $query->rowCount();
break;
case 'single':
$data = $query->fetch(PDO::FETCH_ASSOC);
break;
default:
$data = '';
}
}else{
if($query->rowCount() > 0){
$data = $query->fetchAll();
}
}
return !empty($data)?$data:false;
}
Function used with where and Search condition
if(!empty($_POST['customer_number'])) {
$ajaxData = $auth_user->getRows(
'tablename',
array('where' => array('fieldName'=>$doc)),
array('search'=> array('fieldname1'=>$_POST['customer_number'], 'fieldname2'=>$_POST['customer_number']))
);
}
Result of the above code is
SELECT * FROM tablename WHERE cust_consum_type = '1'
Expected Result is.
select * from tablename where fieldName='somevalue' and fieldname1='somevalue' OR fieldname2='somevalue'
Help me to fix this issue.
This function is so wrong on so many levels, being critically insecure in the first place.
Instead, use vanilla PDO. Make your function this way
public function getRows($sql,$input = array()){
$stmt = $this->conn->prepare($sql);
$stmt->execute($input);
return $stmt;
}
Then just write your query right away with placeholders, pass the data in pparameters and have the result:
$sql = "select * from tablename where fieldName=:fieldName
and (fieldname1=:fieldName1 OR fieldname2=:fieldName2)";
$input = ['fieldName'=>$doc,
'fieldname1'=>$_POST['customer_number'],
'fieldname2'=>$_POST['customer_number']];
$data = $db->getRows($sql, $input)->fetchAll();
it will be safe, clean, always working, safe, flexible, safe from SQL injections and syntax errors.

How can I use this function?I take it from other project

I am new to php language. I just copy a database connection function from another sample project. The code is below.
public function getRows($conditions = array()){
$sql = 'SELECT ';
$sql .= array_key_exists("select",$conditions)?$conditions['select']:'*';
$sql .= ' FROM '.$this->table;
if(array_key_exists("where",$conditions)){
$sql .= ' WHERE ';
$i = 0;
foreach($conditions['where'] as $key => $value){
$pre = ($i > 0)?' AND ':'';
$sql .= $pre.$key." = '".$value."'";
$i++;
}
}
if(array_key_exists("order_by",$conditions)){
$sql .= ' ORDER BY '.$conditions['order_by'];
}
if(array_key_exists("start",$conditions) && array_key_exists("limit",$conditions)){
$sql .= ' LIMIT '.$conditions['start'].','.$conditions['limit'];
}elseif(!array_key_exists("start",$conditions) && array_key_exists("limit",$conditions)){
$sql .= ' LIMIT '.$conditions['limit'];
}
$query = $this->db->prepare($sql);
$query->execute();
if(array_key_exists("return_type",$conditions) && $conditions['return_type'] != 'all'){
switch($conditions['return_type']){
case 'count':
$data = $query->rowCount();
break;
case 'single':
$data = $query->fetch(PDO::FETCH_ASSOC);
break;
default:
$data = '';
}
}else{
if($query->rowCount() > 0){
$data = $query->fetchAll();
}
}
return !empty($data)?$data:false;
}
Can anyone show me example how to use this function?I want to use WHERE,LIMIT,GROUP_BY and SELECT clauses. When I put in an array like this, I got error message " Invalid argument supplied for foreach()"
$conditions = array('where' => "user_name = '$username'");
$data = $userMo -> getRows($conditions);
you are making a mistake, as its said Invalid argument supplied for foreach()
that means its not getting an array, and think if there are multiple WHERE then??
so try this
$conditions = array('where' => array('user_name' => $username));

PHP mysqli table query gives multiple results that i want to query against another table

I have been working on a social network, i have a fanpages table that a user can create a profile for their favorite band or celebrity and another table called friends where they can subscribe to the fanpages. i then want the requests to appear in notifications for the fanpage admin to except.
after the first sql query it returns fanpages with multiple values but if i echo the next $sql query it shows that its only selecting one result to query instead of all of them.
so basically i need to query fanpages table for all fanpages created_by the user logged on ($log_username), then i need to take those fanpages and query the friends table to find out if anyone has requested to subscribe to the users fan pages??
thanks for your help Michael
<?php
$fanpage_requests = '';
$fansql = "SELECT created_by, fanpage_name FROM `fanpages` WHERE created_by = '$log_username' ";
$fanquery = mysqli_query($db_conx, $fansql);
$fannumrows = mysqli_num_rows($fanquery);
if($fannumrows < 1){
$fanpage_requests = 'No friend requests';
} else {
while($row = mysqli_fetch_array($fanquery, MYSQLI_ASSOC)) {
$fanpage_name = $row["fanpage_name"];
$created_by = $row["created_by"];
$fansubSql = "SELECT * FROM friends WHERE user2='$fanpage_name' AND accepted='0' ORDER BY datemade ASC";
$fansubQuery = mysqli_query($db_conx, $fansubSql);
$fansubNumrows = mysqli_num_rows($fansubQuery);
//print_r ($fansubNumrows);
if($fansubNumrows < 1){
$fanpage_requests = "blah blah";
}
print_r ($fansubNumrows);
while ($fansubRow = mysqli_fetch_array($fansubQuery, MYSQLI_ASSOC)) {
$fansubreqID = $fansubRow["id"];
$fansubuser1 = $fansubRow["user1"];
$fansubdatemade = $fansubRow["datemade"];
$fansubdatemade = strftime("%B %d", strtotime($fansubdatemade));
$fansubthumbquery = mysqli_query($db_conx, "SELECT avatar FROM users WHERE username='$fansubuser1' LIMIT 1");
$fansubthumbrow = mysqli_fetch_row($fansubthumbquery);
$fansubuser1avatar = $fansubthumbrow[0];
$fansubuser1pic = '<img src="user/'.$fansubuser1.'/'.$fansubuser1avatar.'" alt="'.$fansubuser1.'" class="user_pic">';
if($fansubuser1avatar == NULL){
$fansubuser1pic = '<img src="images/avatardefault.jpg" alt="'.$fansubuser1.'" class="user_pic">';
}
$fanpage_requests .= '<div id="friendreq_'.$fansubreqID.'" class="friendrequests">';
$fanpage_requests .= ''.$fansubuser1pic.'';
$fanpage_requests .= '<div class="user_info" id="user_info_'.$fansubreqID.'">'.$fansubdatemade.' '.$fansubuser1.' requests friendship<br /><br />';
$fanpage_requests .= '<button onclick="fanReqHandler(\'accept\',\''.$fansubreqID.'\',\''.$fansubuser1.'\',\'user_info_'.$fansubreqID.'\')">accept</button> or ';
$fanpage_requests .= '<button onclick="fanReqHandler(\'reject\',\''.$fansubreqID.'\',\''.$fansubuser1.'\',\'user_info_'.$fansubreqID.'\')">reject</button>';
$fanpage_requests .= '</div>';
$fanpage_requests .= '</div>';
}
}
}
?>
print_r output is now 001110 and i get blah blah
Ok, so having established that you need to close your loop later, the reason it does not work correctly is because now you are using the same variables in the different loops, so values are being overwritten (e.g. $query).
You need to differentiate your loops clearly, in terms of all variables that need to be different:
<?php
$friend_requests = '';
$sql = "SELECT created_by, fanpage_name FROM `fanpages` WHERE created_by = '$log_username' ";
$query = mysqli_query($db_conx, $sql);
$numrows = mysqli_num_rows($query);
if($numrows < 1){
$friend_requests = 'No friend requests';
} else {
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$fanpage_name = $row["fanpage_name"];
$created_by = $row["created_by"];
$friendsSql = "SELECT * FROM friends WHERE user2='$fanpage_name' AND accepted='0' ORDER BY datemade ASC";
$friendsQuery = mysqli_query($db_conx, $friendsSql);
$friendsNumrows = mysqli_num_rows($friendsQuery);
$fanpage_requests = "$friendsSql";
if($friendsNumrows < 1){
$fanpage_requests = "$fanpage_name"; **//this shows that only 1 query is being queried in this second sql statement**
}
while ($friendsRow = mysqli_fetch_array($friendsQuery, MYSQLI_ASSOC)) {
$reqID = $friendsRow["id"];
$user1 = $friendsRow["user1"];
$datemade = $friendsRow["datemade"];
$datemade = strftime("%B %d", strtotime($datemade));
$thumbquery = mysqli_query($db_conx, "SELECT avatar FROM users WHERE username='$user1' LIMIT 1");
$thumbrow = mysqli_fetch_row($thumbquery);
$user1avatar = $thumbrow[0];
$user1pic = '<img src="user/'.$user1.'/'.$user1avatar.'" alt="'.$user1.'" class="user_pic">';
if($user1avatar == NULL){
$user1pic = '<img src="images/avatardefault.jpg" alt="'.$user1.'" class="user_pic">';
}
$fanpage_requests .= '<div id="friendreq_'.$reqID.'" class="friendrequests">';
$fanpage_requests .= ''.$user1pic.'';
$fanpage_requests .= '<div class="user_info" id="user_info_'.$reqID.'">'.$datemade.' '.$user1.' requests friendship<br /><br />';
$fanpage_requests .= '<button onclick="fanReqHandler(\'accept\',\''.$reqID.'\',\''.$user1.'\',\'user_info_'.$reqID.'\')">accept</button> or ';
$fanpage_requests .= '<button onclick="fanReqHandler(\'reject\',\''.$reqID.'\',\''.$user1.'\',\'user_info_'.$reqID.'\')">reject</button>';
$fanpage_requests .= '</div>';
$fanpage_requests .= '</div>';
}
}
}
?>

Categories