I want to use prepared statements inside DataTables for the code stated below. It has two queries (query and query1).
Query has two "where conditions" which variables are $classid and $searchfield.
Query1 is a "Limit" statement and also has two variables $start and $end.
The results of both queries should be stored in the $data array. At the moment I don't get any results. How do I bind the paramteres correctly in this case and store the results in the array so DataTables gets a working json?
My try:
$connect = mysqli_connect("localhost", "xxxx", "xxx", "xxx");
$columns = array('itemOverview.id', 'itemOverview.Display_lang');
// Variables to bind
$classid = 4;
$searchfield = $_POST["is_searchfield"];
$start = $_POST['start'];
$end = $_POST['length'];
$query = "SELECT * FROM itemOverview INNER JOIN item ON item.id = itemOverview.id";
$query.= " WHERE item.ClassID = ? AND ";
if(!empty($searchfield)) {
$query .= "itemOverview.Display_lang = ? AND ";
}
$query1 = '';
if($_POST["length"] != -1) {
$query1 = 'LIMIT ?, ?';
}
$stmt = mysqli_stmt_init($connect);
if (!mysqli_stmt_prepare($stmt, $query. $query1)) {
echo "SQL Failed";
} else {
// bind paramaters to the placeholder
mysqli_stmt_bind_param($stmt, "ssss", $classid, $searchfield, $start, $end);
// run parameters inside database
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$data = array();
while($row = mysqli_fetch_array($result))
{
$sub_array = array();
$sub_array[] = $row["id"];
$sub_array[] = $row["Display_lang"];
$data[] = $sub_array;
}
}
$output = array(
"draw" => intval($_POST["draw"]),
"data" => $data
);
echo json_encode($output);
Related
{
"idbarang": "ID-75192864",
"namabarang": "Fruit Tea",
"jenisbarang": "Minuman",
"hargabarang": "6000"
}
i try this
<?php
include 'koneksi.php';
$idbarang = $_GET['id'];
if($idbarang == !null){
$query = mysqli_query($conn, "SELECT * FROM data_barang WHERE id_barang = '$idbarang'");
$result = array();
$i= 0;
while($row = mysqli_fetch_array($query)){
$result[$i]['idbarang'] = $row['id_barang'];
$result[$i]['namabarang'] = $row['nama_barang'];
$result[$i]['jenisbarang'] = $row['jenis_barang'];
$result[$i]['hargabarang'] = $row['harga_barang'];
$i++;
};
echo json_encode($result);
} else {
$query = mysqli_query($conn, "SELECT * FROM data_barang");
$result = array();
$i= 0;
while($row = mysqli_fetch_assoc($query)){
$result[$i]['idbarang'] = $row['id_barang'];
$result[$i]['namabarang'] = $row['nama_barang'];
$result[$i]['jenisbarang'] = $row['jenis_barang'];
$result[$i]['hargabarang'] = $row['harga_barang'];
$i++;
};
echo json_encode($result);
}
?>
and this the result
[
{
"idbarang": "ID-75192864",
"namabarang": "Fruit Tea",
"jenisbarang": "Minuman",
"hargabarang": "6000"
},
{
"idbarang": "ID-96037284",
"namabarang": "Sampoerna",
"jenisbarang": "Rokok",
"hargabarang": "12000"
}
]
I think you are asking why you are always going through the ELSE and never the IF. Thats because of this IF test
if($idbarang == !null){
Instead try
<?php
include 'koneksi.php';
if(!empty($_GET['id'])){
$idbarang = $_GET['id'];
You could also simplify that code quite a lot, and protect it from SQL Injection.
// Do the renaming of column names as part of the query
$sql = 'SELECT id_barang as idbarang, nama_barang as namabarang,
jenis_barang as jenisberang, jenis_barang as hargabarang
FROM data_barang';
if(!empty($_GET['id'])){
// add the WHERE clause on to the base query
$sql .= ' WHERE id_barang = ?';
$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $_GET['id']);
$stmt->execute();
$res = $stmt->get_result();
} else {
$res = $conn->query($sql);
}
// as the renaming is done we can just fetch all the results and convert to a JSON document
$result = $res->fetch_all(MYSQLI_ASSOC);
echo json_encode($result);
Sometimes my script receives a $_POST["is_searchfield"] request from a form. Then I want to use this variable as a part of a "Where" clause of a MySQL query. Otherwise this part of the "Where" clause shouldn't afflict the rest of the query.
For the query I use a prepared statement.
If the $_POST["is_searchfield"] has a value the query works as expected, but if no variable is sent the whole query doesn't give me any results.
How can I achieve that an empty variable doesn't destroy the whole query and only this certain part of the "where" clause will be ignored. Also the prepared statement should continue to work.
I tried to check if the variable is set with !empty but it doesn't change this behavoiur.
$conn = new mysqli("localhost", "xxxx", "xxxx", "xxxx");
$conn->set_charset("utf8");
// Variables to bind
$classid = "4";
if(!empty($_POST["is_searchfield"]))
{
$searchfield = $_POST["is_searchfield"];
}
else {
$searchfield= "";
}
$fileid = "10";
$sqlitemsparse = "SELECT * FROM itemSparse INNER JOIN item ON item.id = itemSparse.id";
$sqlitemsparse .= " WHERE item.ClassID = ?";
$sqlitemsparse .= " AND itemSparse.Display_lang = ?";
$sqlitemsparse .= " AND itemSparse.fileid = ?";
$sqlitemsparse2 = " LIMIT 0, 10";
$stmt = $conn->prepare($sqlitemsparse . $sqlitemsparse2);
$stmt->bind_param('sss', $classid, $searchfield, $fileid);
$stmt->execute();
$resultitemsparse = $stmt->get_result();
$rowsitemsparse = $resultitemsparse->fetch_all(MYSQLI_ASSOC);
The idea is to change the query to match the data provided
$conn = new mysqli("localhost", "xxxx", "xxxx", "xxxx");
$conn->set_charset("utf8");
// Variables to bind
$classid = "4";
$fileid = "10";
if(!empty($_POST["is_searchfield"]))
{
$sqlitemsparse = "SELECT *
FROM itemSparse
INNER JOIN item ON item.id = itemSparse.id
WHERE item.ClassID = ?
AND itemSparse.Display_lang = ?
AND itemSparse.fileid = ?
LIMIT 0, 10";
$stmt = $conn->prepare($sqlitemsparse);
$stmt->bind_param('sss', $classid, $_POST["is_searchfield"], $fileid);
} else {
$sqlitemsparse = "SELECT *
FROM itemSparse
INNER JOIN item ON item.id = itemSparse.id
WHERE item.ClassID = ?
AND itemSparse.fileid = ?
LIMIT 0, 10";
$stmt = $conn->prepare($sqlitemsparse);
$stmt->bind_param('ss', $classid, $fileid);
}
$stmt->execute();
$resultitemsparse = $stmt->get_result();
$rowsitemsparse = $resultitemsparse->fetch_all(MYSQLI_ASSOC);
I need help with converting this SQL to Prepared Statement. This is for my search bar. I hope I'll be able to receive some help as I am a beginner in this.
This is my SQL
$conn = mysqli_connect('localhost','root','','my_db');
$mysql = "SELECT * FROM catetable";
$bike_list = mysqli_query($conn,$mysql);
$catesql = "SELECT catename FROM catetable";
$cate_list = mysqli_query($conn,$catesql);
And this is what I would like to change to Prepared Statement
if (isset($_GET['search']))
{
$search = $_GET['search'];
$searchlist = array();
$lowersearchlist = array();
$i = 0;
while ($one_cate = mysqli_fetch_assoc($cate_list))
{
$searchlist[$i] = $one_cate['catename'];
$lowersearchlist[$i] = strtolower($one_cate['catename']);
$i++;
}
if (in_array($search,$searchlist) || in_array($search,$lowersearchlist))
{
header("Location:feature.php");
}
else
{
header("Location:index.php?error=true");
}
}
Write a query that matches the parameter in the WHERE clause. MySQL normally defaults to case-insensitive comparisons, so you don't need to fetch all the rows to compare them exactly and case-insensitively.
if (isset($_GET['search'])) {
$stmt = $conn->prepare("SELECT COUNT(*) AS c FROM yourTable WHERE catename = ?");
$stmt->bind_param("s", $_GET['search']);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
if ($row['c'] > 0) {
header("Location: feature.php");
} else {
header("Location: index.php?error=true";
}
}
Trying to get a function working to create simple CRUD "Select" with multiple parameters to any table. I think I got the hardest part, but couldn't fetch the data right now. Maybe I'm doing something wrong I can't figure out.
My prepared statement function:
function prepared_query($mysqli, $sql, $params, $types = ""){
$types = $types ?: str_repeat("s", count($params));
if($stmt = $mysqli->prepare($sql)) {
$stmt->bind_param($types, ...$params);
$stmt->execute();
return $stmt;
} else {
$error = $mysqli->errno . ' ' . $mysqli->error;
error_log($error);
}
}
The query creator:
function create_select_query($table, $condition = "", $sort = "", $order = " ASC ", $clause = ""){
$table = escape_mysql_identifier($table);
$query = "SELECT * FROM ".$table;
if(!empty($condition)){
$query .= create_select_query_where($condition,$clause);
}
if(!empty($sort)){
$query .= " ORDER BY ".$sort." $order";
}
return $query;
}
The helper function to create the WHERE clause:
function create_select_query_where($condition,$clause){
$query = " WHERE ";
if(is_array($condition)){
$pair = array();
$size = count($condition);
$i = 0;
if($size > 1){
foreach($condition as $field => $val){
$i++;
if($size-1 == $i){
$query .= $val." = ? ".$clause. " ";
}else{
$query .= $val." = ? ";
}
}
}else{
foreach($condition as $field => $val){
$query .= $val." = ? ";
}
}
}else if(is_string($condition)){
$query .= $condition;
}else{
$query = "";
}
return $query;
}
The select function itself:
function crud_select($conn, $table, $args, $sort, $order, $clause){
$sql = create_select_query($table, array_keys($args),$sort, $order, $clause);
print_r($sql);
if($stmt = prepared_query($conn, $sql, array_values($args))){
return $stmt;
}else{
$errors [] = "Something weird happened...";
}
}
When I create the query, it seems to be OK but can't fetch the data. If I create an array with only one argument the query translates into:
SELECT * FROM `teste_table` WHERE id = ?
If I create with multiple parameters, it turns like this:
SELECT * FROM `teste_table` WHERE id = ? AND username = ?
So, how can I properly fetch the data from the select. This should be used for multiple purposes, so I could get more than one result, so the best way would be fetch data as array I guess.
I guess I'm close, but can't figure it out. Thanks
I told you to limit your select function to a simple primary key lookup. And now you opened a can of worms. As a result you are getting entangled implementation code and unreadable application code.
$table, $args, $sort, $order, $clause
What all these variables are for? How you're going to call this function - a list of gibberish SQL stubs in a random order instead of plain and simple SQL string? And how to designate a list of columns to select? How to use JOINS? SQL functions? Aliases? Why can't you just write a single SQL statement right away? You already have a function for selects, though without this barbaric error reporting code you added to it:
function prepared_query($mysqli, $sql, $params, $types = ""){
$types = $types ?: str_repeat("s", count($params));
$stmt = $mysqli->prepare($sql)) {
$stmt->bind_param($types, ...$params);
$stmt->execute();
return $stmt;
}
Just stick to it and it will serve you all right.
$sql = "SELECT * FROM `teste_table` WHERE id = ? AND username = ?";
$stmt = prepared_query($mysqli, $sql, [$id, $name]);
$row = $stmt->get_result()->fetch_assoc();
The only specific select function could be, again, a simple primary key lookup:
function crud_find($conn, $table, $id)
{
$table = escape_mysql_identifier($table);
$sql = "SELECT * FROM $table WHERE id=?";
$stmt = prepared_query($conn, $sql, [$id], "i");
return $stmt->get_result()->fetch_assoc();
}
And for the everything else just use a generic function with native SQL.
I'm using php to get data from database, but i have a problem.
First of all, It is php file which gets data from database.
<?php
$con = mysqli_connect(mydatabase_address, myid, password);
$userLocation = $_POST["userLocation"];
$stmt = mysqli_prepare($con, "SELECT * FROM neighborTable WHERE postLocation = ?");
mysqli_stmt_bind_param($stmt, "s", $userLocation);
mysqli_execute($stmt);
mysqli_stmt_bind_result($stmt, $ID, $postWriter, $postContent, $postDate, $postPic, $postLike, $postComments, $postLocation, $profilePic, $postGatherDate, $postGatherLocation, $postGatherTime);
$response = array();
while($row = mysqli_stmt_fetch($stmt)) {
$row_array['ID'] = $ID;
$row_array['postWriter'] = $postWriter;
$row_array['postContent'] = $postContent;
$row_array['postDate'] = $postDate;
$row_array['postPic'] = $postPic;
$row_array['postLike'] = $postLike;
$row_array['postComments'] = $postComments;
$row_array['postLocation'] = $postLocation;
$row_array['profilePic'] = $profilePic;
$row_array['postGatherDate'] = $postGatherDate;
$row_array['postGatherLocation'] = $postGatherLocation;
$row_array['postGatherTime'] = $postGatherTime;
array_push($response, $row_array);
}
echo json_encode(array("response"=>$response), JSON_UNESCAPED_UNICODE);
mysqli_close($con);
?>
However, it returns like below. It has correct number of data, but its values are all null. How can i solve this problem?
{"response":[{"ID":null,"postWriter":null,"postContent":null,"postDate":null,"postPic":null,"postLike":null,"postComments":null,"postLocation":null,"profilePic":null,"postGatherDate":null,"postGatherLocation":null,"postGatherTime":null},{"ID":null,"postWriter":null,"postContent":null,"postDate":null,"postPic":null,"postLike":null,"postComments":null,"postLocation":null,"profilePic":null,"postGatherDate":null,"postGatherLocation":null,"postGatherTime":null},{"ID":null,"postWriter":null,"postContent":null,"postDate":null,"postPic":null,"postLike":null,"postComments":null,"postLocation":null,"profilePic":null,"postGatherDate":null,"postGatherLocation":null,"postGatherTime":null}]}