Select query php sql injection - php

I'm doing a test on a code that I had previously written, my goal is to write safer queries but I don't understand why it doesn't work
working query:
$zero = 0;
$inviata = "SI";
$token_inserito = "NO";
$richiesta_non_scaduta = "NO";
$categoria_professionista = $_SESSION['categoria_collaboratore'];
$oggi = date('Y-m-d');
$query_string = "SELECT *
FROM richieste
LEFT JOIN cat_professionisti
ON richieste.categoria_richiesta = cat_professionisti.ID_cat_prof
WHERE richieste.categoria_richiesta = cat_professionisti.ID_cat_prof
AND richieste.ID_Collaboratore = 0
AND richieste.inviata = 'SI'
AND richieste.token_inserito = 'NO'
AND richieste.richiesta_scaduta = 'NO'
AND richieste.categoria_richiesta = '$categoria_professionista'
AND richieste.scadenza_richiesta >= '$oggi'
";
$query_richieste_disponibili = mysqli_query($connessione, $query_string);
<?php while($row = mysqli_fetch_assoc($query_richieste_disponibili)){ ?>
......
<?php } ?>
query not working:
$zero = 0;
$inviata = "SI";
$token_inserito = "NO";
$richiesta_non_scaduta = "NO";
$categoria_professionista = $_SESSION['categoria_collaboratore'];
$oggi = date('Y-m-d');
$query = $connessione->prepare("
SELECT *
FROM richieste
LEFT JOIN cat_professionisti
ON richieste.categoria_richiesta = cat_professionisti.ID_cat_prof
WHERE richieste.categoria_richiesta = cat_professionisti.ID_cat_prof
AND richieste.ID_Collaboratore = ?
AND richieste.inviata = ?
AND richieste.token_inserito = ?
AND richieste.richiesta_scaduta = ?
AND richieste.categoria_richiesta = ?
AND richieste.scadenza_richiesta >= ?");
$query->bind_param('isssii', $zero, $inviata, $token_inserito, $richiesta_non_scaduta, $categoria_professionista, $oggi);
$query_richieste_disponibili = $query->execute();
<?php while($row = mysqli_fetch_assoc($query_richieste_disponibili)){ ?>
......
<?php } ?>
as I repeat my intent is to write queries against sql injection and therefore safer
edit for #Barmar
$zero = 0;
$inviata = "SI";
$token_inserito = "NO";
$richiesta_non_scaduta = "NO";
$categoria_professionista = $_SESSION['categoria_collaboratore'];
$oggi = date('Y-m-d');
$query = $connessione->prepare("
SELECT *
FROM richieste
LEFT JOIN cat_professionisti
ON richieste.categoria_richiesta = cat_professionisti.ID_cat_prof
WHERE richieste.categoria_richiesta = cat_professionisti.ID_cat_prof
AND richieste.ID_Collaboratore = ?
AND richieste.inviata = ?
AND richieste.token_inserito = ?
AND richieste.richiesta_scaduta = ?
AND richieste.categoria_richiesta = ?
AND richieste.scadenza_richiesta >= ?");
$query->bind_param('isssii', $zero, $inviata, $token_inserito, $richiesta_non_scaduta, $categoria_professionista, $oggi);
$query_richieste_disponibili = $query->execute();
<?php
if ($query->execute()) {
$query_richieste_disponibili = $query->get_result();
while($row = $query_richieste_disponibili->fetch_assoc()) { ?>
<?php }
} ?>
I followed your code that you kindly wrote together with the explanation but when I report it it doesn't work, where am I wrong?

$query->execute() doesn't return a result object, it returns TRUE or FALSE. You need to call $query->get_result to get a result that you can fetch rows from.
And since $oggi is a string, you need the s type in bind_param().
$query->bind_param('isssis', $zero, $inviata, $token_inserito, $richiesta_non_scaduta, $categoria_professionista, $oggi);
if ($query->execute()) {
$query_richieste_disponibili = $query->get_result();
while($row = $query_richieste_disponibili->fetch_assoc()) { ?>
......
<?php }
}
Note that it only works this way if you use the mysqlnd driver. If not, you have to use $query->bind_result() and $query->fetch().

Related

How to make json like this from database mysql using php

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

Normal SQLi statement to Prepared Statement Troubleshoot

I've been trying (to no end) to convert the following normal SQLi statement & after hours of trying I'm still not able to see where I'm going wrong. The statement is as follows:
$get_comments = mysqli_query($con, "SELECT * FROM blog_post_comments WHERE post_id='$post_id' AND removed='no' ORDER BY id ASC");
$count = mysqli_num_rows($get_comments);
if ($count != 0) {
while($comment = mysqli_fetch_array($get_comments)) {
$comment_body = $comment['post_body'];
$posted_to = $comment['posted_to'];
$posted_by = $comment['posted_by'];
$date_added = $comment['date_added'];
$removed = $comment['removed'];
$blog_comment_id = $comment['id'];
etc... }
Here is the latest version of what I have for the prepared statement:
$no = 'no';
$get_comments = mysqli_prepare($con, "SELECT * FROM blog_post_comments WHERE post_id=? AND removed=? ORDER BY id ASC");
$get_comments->bind_param('is', $post_id, $no);
$get_comments->execute();
$result = $get_comments->get_result();
$count = $result->num_rows;
$get_comments->free_result();
if ($count != 0) {
while($comment = $result->fetch_assoc()) {
$comment_body = $comment['post_body'];
$posted_to = $comment['posted_to'];
$posted_by = $comment['posted_by'];
$date_added = $comment['date_added'];
$removed = $comment['removed'];
$blog_comment_id = $comment['id'];
etc... }
Can anyone see if I'm missing something here? In the second statement, I'm not getting an error, but I'm also not loading any posts to display.

PHP: Reuse JQGrid response for Displaying data in DataTable

First of all I am using JQGrid in my application. After changing my CSS to Bootstrap CSS.
I have to use DataTable. I want to reuse my controller pages which makes query to display the data in JQGrid.
Here is my controller page.
<?php
require_once("JsonHeader.php");
$at = $_SESSION['abc'];
$start_date = $_SESSION['start_date'];
$end_date = $_SESSION['end_date'];
if ($_SESSION['list'] == '-1') {
$user_query = "";
} else {
$user_list = $_SESSION['list'];
$user_query = " AND a.user_id IN ($list)";
}
$start_date = $_SESSION['start_date'];
$end_date = $_SESSION['end_date'];
if ($_SESSION['list'] == '-1') {
$user_query = "";
} else {
$user_list = $_SESSION['list'];
$user_query = " AND a.user_id IN ($list)";
}
$page = $_GET['page']; // get the requested page
$limit = $_GET['rows']; // get how many rows we want to have into the grid
$sidx = $_GET['sidx']; // get index row - i.e. user click to sort
$sord = $_GET['sord']; // get the direction
$qtype = ''; // Search column
$query = ''; // Search string
if (isset($_GET['searchField'])) {
$qtype = mysql_real_escape_string($_GET['searchField']);
}
if (isset($_GET['searchString'])) {
$query = mysql_real_escape_string($_GET['searchString']);
}
if (isset($_GET['searchOper'])) {
switch ($_GET['searchOper']) {
case 'eq':
$oper = '=';
$query = mysql_real_escape_string($_GET['searchString']);
break;
case 'ne':
$oper = '!=';
$query = mysql_real_escape_string($_GET['searchString']);
break;
case 'cn':
$oper = 'like';
$query = "%".mysql_real_escape_string($_GET['searchString'])."%";
break;
}
}
$searchSql1 = ($qtype != '' && $query != '') ? "and $qtype $oper '$query'" : '';
if (!$sidx)
$sidx = 1; // connect to the database
$result = mysql_query(sprintf("SELECT ae.col1,ae.col2,ae.col3, ae.col4,ae.col5,ae.col6,ae.col7,a.col8,a.col9,r.col10,p.col11
FROM $tablename3 ae,$tableName a, $tablename1 p, $tablename2 r
WHERE ae.col1=$at $searchSql1
AND a.col1 = $at
AND a.col5=r.col5
AND a.col6=p.col6
$user_query"));
$row = mysql_num_rows($result);
$count = $row;
if ($count > 0) {
$total_pages = ceil($count / $limit);
} else {
$total_pages = 0;
}
if ($page > $total_pages)
$page = $total_pages; $start = $limit * $page - $limit; // do not put
$limit * ($page - 1);
$SQL = sprintf("SELECT ae.col1,ae.col2,ae.col3, ae.col4,ae.col5,ae.col6,ae.col7,a.col8,a.col9,r.col10,p.col11
FROM $tablename3 ae,$tableName a, $tablename1 p, $tablename2 r
WHERE ae.col1=$at $searchSql1
AND a.col1 = $at
AND a.col5=r.col5
AND a.col6=p.col6
$query");
$result = mysql_query($SQL) or die("Couldn t execute query." . mysql_error());
$responce = new stdClass();
$responce->page = new stdClass();
$responce->total = new stdClass();
$responce->records = new stdClass();
$responce->page = $page;
$responce->total = $total_pages;
$responce->records = $count;
$i = 0;
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$responce->rows[$i]['id'] = $row['col1'];
$responce->rows[$i]['cell'] = array($row['col1'], $row['col2'], $row['col3'], $row['col4'], $row['col5'], $row['col6'], $time, $row['col7']);
$i++;
}
echo json_encode($responce);
?>
HOW can I change this for DataTable?.
Please provide me the best way...
Finally I found how to resue my controller page for DataTable. Simply change the post variables in the controller page.
Like
$_GET['page']; By $_REQUEST['sEcho']
$_GET['rows']; By $_REQUEST['iDisplayStart'],$_REQUEST['iDisplayLength']
$_GET['sord']; $_REQUEST['sSortDir_0']
$_GET['searchString']: $_GET['sSearch']:
And some changes the json response like
$ans['iTotalRecords'] = $count;
$ans['iTotalDisplayRecords'] = $count;
$ans['aaData'] = $aadata;
echo json_encode($ans);

PHP-MYSQL Every time a specific row hits it adds +1 to PHP variable

Here's what I currently have to get the values from database
$unread_messages = "";
$query = mysql_query("SELECT * FROM pm WHERE msg_to='".$_SESSION['user_id']."' or
msg_from='".$_SESSION['user_id']."' LIMIT 10") or die(mysql_error());
while($row = mysql_fetch_array($query)){
$msg_id = $row["msg_id"];
$msg_to = $row["msg_to"];
$msg_from = $row["msg_from"];
$msg_title = $row["msg_title"];
$msg_content = $row["msg_content"];
$msg_date = $row["msg_date"];
$msg_read = $row["msg_read"];
}
now I need it so that everytime '$msg_read == 1' it adds +1 to '$unread_messages'. Can somebody help me ?
Just add a check in your loop
$unread_messages = 0;
while ( ... ) {
// do stuff
if ($msg_read == 1) {
$unread_messages++;
}
}
I highly recommend that you take a look at the mysqli or PDO extensions for database access. mysql_ is outdated and should not be used.
have you tried this one ?
$unread_messages = "";
$query = mysql_query("SELECT * FROM pm WHERE msg_to='".$_SESSION['user_id']."' or
msg_from='".$_SESSION['user_id']."' LIMIT 10") or die(mysql_error());
while($row = mysql_fetch_array($query)){
$msg_id = $row["msg_id"];
$msg_to = $row["msg_to"];
$msg_from = $row["msg_from"];
$msg_title = $row["msg_title"];
$msg_content = $row["msg_content"];
$msg_date = $row["msg_date"];
$unread_messages = ($row["msg_read"]==1 && $unread_messages=='') ? $unread_messages=1 : $unread_messages=$unread_messages+1;
}
ohh, im sorry, using PDO actualy really good practice, may be you can try this
$unread_messages = "";
try {
$dbh = new PDO("mysql:host=$hostname;dbname=dbname", $username, $password);
$sql = "SELECT * FROM pm WHERE msg_to='".$_SESSION['user_id']."' or msg_from='".$_SESSION['user_id']."' LIMIT 10";
foreach ($dbh->query($sql) as $row){
$unread_messages = ($row["msg_read"]==1 && $unread_messages=='') ? $unread_messages=1 : $unread_messages=$unread_messages+1;
}
$dbh = null;
}
catch(PDOException $e){
echo $e->getMessage();
}
$unread_message = 0;
while($row = mysql_fetch_array($query))
{
//Your code
if ($msg_read === 1)
$unread_message++;
}

SQL won't work? It doesn't come up with errors either

I have PHP function which checks to see if variables are set and then adds them onto my SQL query. However I am don't seem to be getting any results back?
$where_array = array();
if (array_key_exists("location", $_GET)) {
$location = addslashes($_GET['location']);
$where_array[] = "`mainID` = '".$location."'";
}
if (array_key_exists("gender", $_GET)) {
$gender = addslashes($_GET["gender"]);
$where_array[] = "`gender` = '".$gender."'";
}
if (array_key_exists("hair", $_GET)) {
$hair = addslashes($_GET["hair"]);
$where_array[] = "`hair` = '".$hair."'";
}
if (array_key_exists("area", $_GET)) {
$area = addslashes($_GET["area"]);
$where_array[] = "`locationID` = '".$area."'";
}
$where_expr = '';
if ($where_array) {
$where_expr = "WHERE " . implode(" AND ", $where_array);
}
$sql = "SELECT `postID` FROM `posts` ". $where_expr;
$dbi = new db();
$result = $dbi->query($sql);
$r = mysql_fetch_row($result);
I'm trying to call the data after in a list like so:
$dbi = new db();
$offset = ($currentpage - 1) * $rowsperpage;
// get the info from the db
$sql .= " ORDER BY `time` DESC LIMIT $offset, $rowsperpage";
$result = $dbi->query($sql);
// while there are rows to be fetched...
while ($row = mysql_fetch_object($result)){
// echo data
echo $row['text'];
} // end while
Anyone got any ideas why I am not retrieving any data?
while ($row = mysql_fetch_object($result)){
// echo data
echo $row->text;
} // end while
I forgot it wasn't coming from an array!

Categories