PHP Mysqli Query execute from table data query - php

I have sql query that saved on table.
tbl_query
SELECT SUM(simpanan_wajib) AS TOTAL FROM tb_simpanan WHERE badgeid_fk = '$getBadgeID'
Then on PHP code:
$query = mysqli_query($con, "SELECT * FROM tbl_query");
while($data = mysqli_fetch_array($query))
{
//SELECT SUM(simpanan_wajib) AS TOTAL FROM tb_simpanan WHERE badgeid_fk = '$getBadgeID'
$getQuery = $data['sql_query'];
$qTotal = mysqli_query($con, $getQuery);
$dTotal = mysqli_fetch_array($qTotal);
echo $dTotal['TOTAL'];
}
When I tried to run that code, it show me result of total is 0. But if I remove this WHERE badgeid_fk = '$getBadgeID' on query data, the result is OK not 0.
How to keep execute the query even if there is an variable '$getBadgeID'

PHP treating this variable as a string, thats why result generating this query
SELECT SUM(simpanan_wajib) AS TOTAL FROM tb_simpanan WHERE badgeid_fk = '$getBadgeID' // its not converting your variable with 150502
Here you can use alternate name or you can use with delimiter like:
Your current query is:
SELECT SUM(simpanan_wajib) AS TOTAL FROM tb_simpanan WHERE badgeid_fk = '$getBadgeID'
Change your query with:
SELECT SUM(simpanan_wajib) AS TOTAL FROM tb_simpanan WHERE badgeid_fk = ':getBadgeID'
Now, you need to use str_replace to replace delimiter with your variable like:
while($data = mysqli_fetch_array($query))
{
$getQuery = str_replace(":getBadgeID", $getBadgeID , $data['sql_query']);
}
Why i am using delimiter here, because your variable $getBadgeID having defined value inside your php script and its not dynamic.
In our chat conversation, #executable suggest an another solution to use prepared statement.
Edit:
As per discussion with #Bananaapple, i am adding this comment for future visitors, Prepared Statement is an another solution which is more secure, if you want to avoid SQL injection, then choose prepared statement.

The recommend way is to use the prepared statements to sanitize the query and protect you from SQL injection. The following comic give an example of what is SQL injection.
For answering the question we discover that in your query the variable $getBadgeID was read as text and not as variable. I recommend you to use this code which use the prepared statements :
<?php
$conn = new mysqli("HOST", "USER", "SECRET", "DATABASE");
if($stmt = $conn->prepare("SELECT SUM(simpanan_wajib) AS TOTAL FROM tb_simpanan WHERE badgeid_fk = ?")) {
$stmt->bind_param("s", $getBadgeID);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
$total = $row['TOTAL'];
}
$stmt->close();
}
$conn->close();
var_dump($total);
If you want more debugging :
<?php
if(isset($getBadgeID) and $getBadgeID != ""){
$conn = new mysqli("HOST", "USER", "SECRET", "DATABASE");
if($stmt = $conn->prepare("SELECT SUM(simpanan_wajib) AS TOTAL FROM tb_simpanan WHERE badgeid_fk = ?")) {
$stmt->bind_param("s", $getBadgeID);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
$total = $row['TOTAL'];
}
$stmt->close();
}else{
echo "Query is wrong";
}
$conn->close();
var_dump($total);
}else{
echo 'Variable $getBadgeID is empty';
}

Related

Using a query result in another query

This is my first query, i want to use the multiple itemID's extracted for another query.
$conn = new mysqli(server, dbuser, dbpw, db);
$email = $_GET['email'];
$querystring = "SELECT itemID from mycart where email = '".$email."' ";
$result = $conn->query($querystring);
$rs = $result->fetch_array(MYSQLI_ASSOC);
The second query that need
$query = "SELECT * from CatalogueItems where itemID = '".$itemID."'";
How do i make these 2 query run?
Firstly, Your code is open to SQL injection related attacks. Please learn to use Prepared Statements
Now, from a query point of view, you can rather utilize JOIN to make this into a single query:
SELECT ci.*
FROM CatalogueItems AS ci
JOIN mycart AS mc ON mc.itemID = ci.itemID
WHERE mc.email = $email /* $email is the input filter for email */
PHP code utilizing Prepared Statements of MySQLi library would look as follows:
$conn = new mysqli(server, dbuser, dbpw, db);
$email = $_GET['email'];
$querystring = "SELECT ci.*
FROM CatalogueItems AS ci
JOIN mycart AS mc ON mc.itemID = ci.itemID
WHERE mc.email = ?"; // ? is the placeholder for email input
// Prepare the statement
$stmt = $conn->prepare($querystring);
// Bind the input parameters
$stmt->bind_param('s', $email); // 's' represents string input type for email
// execute the query
$stmt->execute();
// fetch the results
$result = $stmt->get_result();
$rs = $result->fetch_array(MYSQLI_ASSOC);
// Eventually dont forget to close the statement
// Unless you have a similar query to be executed, for eg, inside a loop
$stmt->close();
Refer to the first query as a subquery in the second:
$query = "SELECT * from CatalogueItems WHERE itemID IN ";
$query .= "(" . $querystring . ")";
This is preferable to your current approach, because we only need to make one single trip to the database.
Note that you should ideally be using prepared statements here. So your first query might look like:
$stmt = $conn->prepare("SELECT itemID from mycart where email = ?");
$stmt->bind_param("s", $email);
This creates a variable out of your result
$query = "SELECT itemID FROM mycart WHERE email = :email";
$stm = $conn->prepare($query);
$stm->bindParam(':email', $email, PDO::PARAM_STR, 20);
$stm->execute();
$result = $stm->fetchAll(PDO::FETCH_OBJ);
foreach ($result as $pers) {
$itemID = $pers->itemID;
}

store sql statement in MySQL then run it

Is it possible to store the following SQL statement in MySQL then run it in a prepared statement?
Mysql table:
Table name: mystatements
Columns:id, statements
The following syntax is stored in the statements field:
SELECT id, AES_DECRYPT(secret,'$key') as txtsecret
FROM TABLE_1
Now in php:
first: I do a select query to get my statement
$stmt = $mysqli->prepare("SELECT statements FROM mystatements limit 1");
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$statement.=$row['txtstatement'];
}
second: using the variable ($statement) from the the query above and add it to query below to run the in the prepared statement:
$key='password123';
$stmt = $mysqli->prepare($statement);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
echo $row['txtsecret'];
}
Also my stored syntax contains AES_DECRYPT(secret,'$key') just to complicate things. is what i'm trying to achieve possible? have I gone about this completely the wrong way?
Ok..
$key='password123';
$sql = str_replace('$key', $key, $statement); //replace $key to correct value
$stmt = $mysqli->prepare($sql);
Result:
SELECT id, AES_DECRYPT(secret,'$key') as txtsecret FROM TABLE_1
to
SELECT id, AES_DECRYPT(secret,'password123') as txtsecret FROM TABLE_1

PHP prepare and execute

I was using the following code to execute the queries in the database:
$sql = "SELECT * FROM cc_topchoices WHERE location='$location' ORDER BY position asc";
$result = mysqli_query($conn, $sql);
I have read that this way to make the queries is not secure so I want to use the statements prepare() and execute() in php
Now my code looks like this:
$sql = "SELECT * FROM cc_topchoices WHERE location=:location ORDER BY position asc";
$stmt = $conn->prepare($sql);
$stmt->execute(array(":location" => $location));
$result = mysqli_query($conn, $stmt);
But this give me this error:
Fatal error: Call to a member function execute() on boolean
Any idea?
EDIT
Now my code looks like this:
// Create connection
$conn = new PDO("mysql:host=$servername;dbname=$dbname", "$username", "$password");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("set names utf8"); //BECAUSE I NEED TO WORK WITH CHINESE LANGUAGE
$sql = "SELECT * FROM cc_topchoices WHERE location=? ORDER BY position asc";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':location', $location);
$stmt->execute(array($location));
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
if ($result > 0) {
// output data of each row
while($row = $stmt->fetch()) {
echo "<li><div><a href='". $row["rest_url"] ."'><img src='images/top_choices/". $row["image"] ."' alt='". $row["alt_desc"]. "' /></a></div></li>";
}
} else {
echo "0 results";
}
is working :) just need to know if this is a good and secure practice
PDO supports named parameters. MySQLi does not. $stmt is false to show you that the SQL you tried to prepare is syntactically malformed. Use ? instead of :location. Check the MySQLi manual for the correct way to use MySQLi. Or, alternately, switch to PDO.
Use below code to fetch records instead of mysqli_query when using pdo statements if your query returns single row.
$result = $stmt->fetch(PDO::FETCH_ASSOC);
echo $result['db_column'];
And if return multiple rows:
$stmt->setFetchMode(PDO::FETCH_ASSOC);
while ($result = $stmt->fetch()) {
echo $result['db_column'];
}
And one more thing, always put your prepared statement in try{}..catch{} block.
It will work for you.

WHERE statement inside if condition in SQL

Can I do a WHERE clause inside an IF statement?
Like I want something like this:
$SQL = mysql_query("SELECT * FROM `table` ORDER BY `row` DESC");
$rows = mysql_fetch_array($SQL);
$email = $_SESSION['email_of_user'];
if($rows["row"] == "1" WHERE `row`='$email' : ?> (Pulls the logged in user's email)
Edit Server
<?php else : ?>
Add Server
<?php endif; ?>
Do I need (" where the WHERE statement is? Because I tried that and it didn't seem to work...
Or can I do it with an if condition inside of a where clause? Not sure of all these terms yet so correct me if I'm wrong...
You cannot mix up a query statement with PHP's statement. Instead write a query extracting desired results and check if there are any rows from that query.
I will show you an example:
$query = "SELECT * FROM `TABLE_NAME` WHERE `field` = '1' && `email`='$email'"; //Create similar query
$result = mysqli_query($query, $link); //Query the server
if(mysqli_num_rows($result)) { //Check if there are rows
$authenticated = true; //if there is, set a boolean variable to denote the authentication
}
//Then do what you want
if($authenticated) {
echo "Edit Server";
} else {
echo "Add Server";
}
Since Aaron has shown such a effort to encourage safe code in my example. Here is how you can do this securely. PDO Library provides options to bind params to the query statement in the safe way. So, here is how to do it.
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass); //Create the connection
//Create the Query Statemetn
$sth = $dbh->prepare('SELECT * FROM `TABLE_NAME` WHERE field = :field AND email = :email');
//Binds Parameters in the safe way
$sth -> bindParam(':field', 1, PDO::PARAM_INT);
$sth -> bindParam(':email', $email, PDO::PARAM_STRING);
//Then Execute the statement
$sth->execute();
$result = $sth->fetchAll(); //This returns the result set as an associative array

How do I get my database results in an array?

I want to create this array with data from my database..
| Day | Comment | OtherComment |
|-----|---------|--------------|
| 1 | hallo | hallohallo |
|-----|---------|--------------|
| 2 | hey | heyhey |
|-----|---------|--------------|
| 3 | hello | hellohello |
|_____|_________|______________|
I tried a lot of things, but could get the result I wanted, this is my latest code:
$sql = "select DiaryOpmerkingen, DiaryDoctorcomment from tblDiary
WHERE fk_UserId = ".$p_iUserid."
AND DiaryDay = '".$this->Day."';";
$rResult = mysqli_query($link, $sql);
return $rResult;
$dim = array();
while ( $row = mysql_fetch_assoc($result) )
$dim[$row['DiaryOpmerkingen']][$row['DiaryDoctorcomment']] = $row;
Using MySQLi
Okay since we plan to do this using MySQLi, I'd like to introduce you to the object oriented way of using mysqli, so you don't have to keep passing the database link around in your calls. We'll need to make a change to how we connect:
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
if ($mysqli->connect_error) {
// So the user an error instead of exiting like this
// in your production code!
echo "Connect Error ({$mysqli->connect_errno}) {$mysqli->connect_error}";
exit;
}
As noted in the comment inline, instead of exiting and showing the user a very ugly looking single line error, you should instead show them a more friendly error page. Next we're going to use something called a prepared statement to make sure our data is sanitized:
$sql = "SELECT DiaryOpmerkingen, DiaryDoctorcomment FROM tblDiary
WHERE fk_UserId = ?
AND DiaryDay = ?";
$stmt = $mysqli->prepare($sql);
if(!$stmt) {
// Let the user know the query failed!
}
This is a bit unfamiliar looking for those of us used to your standard queries with variables inlined:
$sql = "SELECT DiaryOpmerkingen, DiaryDoctorcomment FROM tblDiary
WHERE fk_UserId = ?
AND DiaryDay = ?";
Basically the question marks act as placeholders that we will fill with the actual values we want. Please note that for string values, you don't need to put quotes around the value:
$sql = "SELECT DiaryOpmerkingen, DiaryDoctorcomment FROM tblDiary
WHERE fk_UserId = ?
AND DiaryDay = '?'"; <-- This is wrong!!
Next is the core of prepared statements:
$stmt->bind_param('is', $p_iUserid, $this->Day);
Here, we are telling MySQLi what we want to replace the question mark placeholders with. The first argument to bind_param indicates the type of data we're replacing. This allows MySQLi to perform sanity checks.
In this case i represents an integer value, and s represents a string value. Then we list our values in the order they appear in the query. $p_iUserid replaces the first ? and $this->Day replaces the second ?. Now we execute this statement so we can get the actual data:
$stmt->execute();
The next part is a very interesting feature:
$stmt->bind_result($diaryOpmerkingen, $diaryDoctorcomment);
This looks complicated at first, but its actually makes things very easier when working with the query. What this function does is create the variables $diaryOpmerkingen and $diaryDoctorcommen fills them with the actual column data when we loop through our results:
$dim = array();
while ($stmt->fetch()) {
$dim[$diaryOpmerkingen][$diaryDoctorcomment] = array($diaryOpmerkingen, $diaryDoctorcomment);
}
Notice how we don't have to use associative arrays and can instead utilize cleaner variable names? Finally, since with prepared statements, you can keep swapping in different values, we need to free our prepared statement once we're done with it:
$stmt->close();
Finally, we close our main database connection:
$mysqli->close();
Here is the full code listing for reference:
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
if ($mysqli->connect_error) {
// So the user an error instead of exiting like this
// in your production code!
echo "Connect Error ({$mysqli->connect_errno}) {$mysqli->connect_error}";
exit;
}
$sql = "SELECT DiaryOpmerkingen, DiaryDoctorcomment FROM tblDiary
WHERE fk_UserId = ?
AND DiaryDay = ?";
$stmt = $mysqli->prepare($sql);
if(!$stmt) {
// Let the user know the query failed!
}
$stmt->bind_param('is', $p_iUserid, $this->Day);
$stmt->execute();
$stmt->bind_result($diaryOpmerkingen, $diaryDoctorcomment);
$dim = array();
while ($stmt->fetch()) {
$dim[$diaryOpmerkingen][$diaryDoctorcomment] = array($diaryOpmerkingen, $diaryDoctorcomment);
}
$stmt->close();
$mysqli->close();
Using Standard MySQL
$sql = "select DiaryOpmerkingen, DiaryDoctorcomment from tblDiary
WHERE fk_UserId = ".$p_iUserid."
AND DiaryDay = '".$this->Day."';";
Only selecting columns you need. Very good. However since we're already using double quotes, we don't need the concatenation operator. Also it's a good idea to break out SQL keywords from column and values consistently:
$sql = "SELECT DiaryOpmerkingen, DiaryDoctorcomment FROM tblDiary
WHERE fk_UserId = $p_iUserid
AND DiaryDay = '{$this->Day}'";
Onward:
$rResult = mysqli_query($link, $sql);
You're mixing up the $link and $sql parameters, and also mixing mysqli and mysql series of functions up. Also unless you have another connection somewhere else, you can just use $sql as the sole parameter:
$rResult = mysql_query($sql);
Now you're returning the result:
return $rResult;
but by doing the the next pieces of code don't get called, so we can get rid of that. Finally we loop through the results:
$dim = array();
while ( $row = mysql_fetch_assoc($rResult) )
{
$dim[$row['DiaryOpmerkingen']][$row['DiaryDoctorcomment']] = $row;
}
Here's the final code:
// Make sure $this->Day is sanitized if it's user input data
$day = mysql_real_escape_string($this->Day);
$sql = "SELECT DiaryOpmerkingen, DiaryDoctorcomment FROM tblDiary
WHERE fk_UserId = $p_iUserid
AND DiaryDay = '$day'";
$rResult = mysql_query($sql);
if(!$rResult) {
//Do something with the error
}
$dim = array();
while ( $row = mysql_fetch_assoc($rResult) )
{
$dim[$row['DiaryOpmerkingen']][$row['DiaryDoctorcomment']] = $row;
}
Check out this page, for some sql functions 5 useful PHP functions for MySQL data fetching
Try:
while ( $r = mysql_fetch_assoc($result) )
$dim[$r['day']] = ["DiaryOpmerkingen" => $r['DiaryOpmerkingen']], 'DiaryDoctorcomment' => [$r['DiaryDoctorcomment']];
$i=0;
while ( $row = mysql_fetch_assoc($result) )
{
extract($row);
$arr[$i]=$DiaryOpmerkingen;
$i++;
$arr[$i]=$DiaryDoctorcomment;
$i++;
}
Please try this code

Categories