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
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.'%") ';
}
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));
I am trying with server side script datatable where I need to add images inside the table. The image path is stored inside the database. I need to display the images in my page. How can I add images in the page. Here is the code.I want the images to be displayed using mysqli and ajax.
<?php
//include connection file
include_once("connection.php");
// initilize all variable
$params = $columns = $totalRecords = $data = array();
$params = $_REQUEST;
//define index of column
$columns = array(
0 =>'id',
1 =>'name',
2=>'images',
3 => 'year',
4 => 'rank'
);
$where = $sqlTot = $sqlRec = "";
// check search value exist
if( !empty($params['search']['value']) ) {
$where .=" WHERE ";
$where .=" (name LIKE '".$params['search']['value']."%' ";
$where .=" OR year LIKE '".$params['search']['value']."%' ";
$where .=" OR id LIKE '".$params['search']['value']."%' ";
$where .=" OR rank LIKE '".$params['search']['value']."%' )";
}
// getting total number records without any search
$sql = "SELECT * FROM `search` ";
$sqlTot .= $sql;
$sqlRec .= $sql;
//concatenate search sql if value exist
if(isset($where) && $where != '') {
$sqlTot .= $where;
$sqlRec .= $where;
}
$sqlRec .= " ORDER BY ". $columns[$params['order'][0]['column']]." ".$params['order'][0]['dir']." LIMIT ".$params['start']." ,".$params['length']." ";
$queryTot = mysqli_query($conn, $sqlTot) or die("database error:". mysqli_error($conn));
$totalRecords = mysqli_num_rows($queryTot);
$queryRecords = mysqli_query($conn, $sqlRec) or die("error to fetch rank holders");
//iterate on results row and create new index array of data
while( $row = mysqli_fetch_row($queryRecords) ) {
$data[] = $row;
$data[] = "<img src =images/".$data[2].">";
$json_data = array(
"draw" => intval( $params['draw'] ),
"recordsTotal" => intval( $totalRecords ),
"recordsFiltered" => intval($totalRecords),
"data" => $data // total data array
);
echo json_encode($json_data); // send data as json format
?>
Because you store the pic in the DB, you can send in ajax the base64 encoding of the pic you want to display.
i'm trying to insert multiple data using a query, i've tried the implode function, the while loop, for loop, but still can't be done..
can u help plz
well i've a combobox box for selecting course name, created a function to get its ID and assign a variable. supose i'm a manager of a department and need to assign all staff below me a course, i select the course, input the date assigned and expected ending date. i've created another field in database to enter the training owner. Since i'm the 1 assigning the course, my name will appear as owner field.
$m_name = $_SESSION['SESS_FIRST_NAME'];
//combobox to get the department ID using variable $dept
//query to get all user concerning the department
$query = mysql_query("select userid from dept_user where dept_id=$dept LIMIT 0, 30 ");
$row= mysql_query($query);
//from here i'm not being able to execute
$qry = mysql_query("INSERT INTO course_detail(userid, course_id, date_assign, expected_end_date, owner) VALUES('$query','$name','$sdate', '$edate', '$m_name')" ) ;
$qry = mysql_query("INSERT INTO course_detail(userid, course_id, date_assign, expected_end_date, owner) VALUES('$query','$name','$sdate', '$edate', '$m_name')" ) ;
So, you're basically trying to insert $query in the userid column. In your code, $query is the result of a mysql select statement, thus a multi-array of user ids. Think of it like a simple SQL query, you can't execute that. Even more, you're doing mysql_query on a mysql_query result, which is plain wrong. Where does the $dept variable come from? What about the others? If you're sure they're valid here's what you need:
// Get the user ids you need to insert in the db
$query = "select userid from dept_user where dept_id=$dept LIMIT 0, 30 "; // this will select the first 30 users in a dept
$buffer = mysql_query($query); // this is a variable that will hold all the results returned by the query above
// While we still have results in the $buffer array, fetch those in the $data array
while ($data = mysql_fetch_assoc($buffer)) {
$insert_query = "INSERT INTO course_detail(userid, course_id, date_assign, expected_end_date, owner) VALUES('".$data['userid']."','$name','$sdate', '$edate', '$m_name')"; // add the userid from the first query and the other data (don't know where you got those
$insert_buffer = mysql_query($insert_query); // execute the statement above, watch out so you don't overwrite the initial $buffer variable
}
// At this point you should have all the data in database
Also, I'm not sure you got the insert statement right
userid > $data['userid'] (ok)
course_id > $name (?!)
date_assign > $sdate (you sure?)
expected_end_date > $edate (ok)
owner > $m_name (ok?)
Make sure you have a good naming convention or else you get lost very easy.
Good luck, a lot of mistakes on just 5 lines of code.
Let's give it a wild guess and assume that this is what you want:
//query to get all user concerning the department
$query = mysql_query("
SELECT userid
FROM dept_user
WHERE dept_id=$dept
");
if(mysql_num_rows($query)){
$insertSQL = "
INSERT INTO course_detail
(userid, course_id, date_assign, expected_end_date, owner)
VALUES
";
$rowsSQL = Array();
while($row = mysql_fetch_row($query)){
$rowsSQL[] = "('{$row['userid']}','$name','$sdate', '$edate', '$m_name')";
}
mysql_query($insertSQL.implode(',', $rowsSQL));
}
Also you should start reading the manual.
Read the doc, you can separate each set of data with a comma.
$values = array();
$values[] = array(
'id' => 1,
'v1' => 'a',
'v2' => 'b'
);
$values[] = array(
'id' => 2,
'v1' => 'c',
'v2' => 'd'
);
$sql = "INSERT INTO course_details (id,v1,v2) VALUES ";
foreach ($values as $value) {
$sql .= '('.$value['id'].','.$value['v1'].','.$value['v2'].'),';
}
$sql = substr ($sql,0,-1) // that will remove the last comma
mysql_query($sql);
Below is the function and here is how to use it
Update Query
$data_array=array(
"bannername" => addslashes($_POST["bannername"]),
"url" => $_POST["url"],
"openin" => $_POST["openin"]
);
$param=" bannerid = '$bannerid'";
$sql=db_makequery("banner",$data_array,"update",$param);
Insert Query
$data_array=array(
"bannername" => addslashes($_POST["bannername"]),
"url" => $_POST["url"],
"openin" => $_POST["openin"]
);
$sql=db_makequery("banner",$data_array);
Function
function db_makequery($table, $data, $action = 'insert', $parameters = '')
{
reset($data);
if ($action == 'insert')
{
$query = 'insert into ' . $table . ' (';
while (list($columns, ) = each($data)) {
$query .= $columns . ', ';
}
$query = substr($query, 0, -2) . ') values (';
reset($data);
while (list(, $value) = each($data))
{
switch ((string)$value)
{
case 'now()':
$query .= 'now(), ';
break;
case 'null':
$query .= 'null, ';
break;
default:
//$query .= '\'' . tep_db_input($value) . '\', ';
$query .= '\'' . $value . '\', ';
break;
}
}
$query = substr($query, 0, -2) . ')';
}
elseif ($action == 'update')
{
$query = 'update ' . $table . ' set ';
while (list($columns, $value) = each($data))
{
switch ((string)$value) {
case 'now()':
$query .= $columns . ' = now(), ';
break;
case 'null':
$query .= $columns .= ' = null, ';
break;
default:
//$query .= $columns . ' = \'' . tep_db_input($value) . '\', ';
$query .= $columns . ' = \'' . $value . '\', ';
break;
}
}
$query = substr($query, 0, -2) . ' where ' . $parameters;
}
return $query;
}