Creating MySQL Prepared Statement - php

I have absolutely zero experience protecting my SQL data. I am trying to prevent injection attacks on my web service by using prepared statements. I've followed several tutorials, but each one I've implemented has killed my PHP script. How could I protect this query?
$value = (integer)$_GET["name"];
$sql = "SELECT `coordinates`, `center` , `content_string` FROM Regions WHERE `id` = {$value}";
$result = $conn->query($sql);
$rows = array();
if ($result->num_rows > 0) {
// output data of each row
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
}
Here is my attempt:
$value = (integer)$_GET["name"];
$sql = $dbConnection->prepare('SELECT `coordinates`, `center` , `content_string` FROM Regions WHERE `id` = ?');
$sql->bind_param('i', $value);
$sql->execute();
$result = $sql->get_result();
$rows = array();
if ($result->num_rows > 0) {
// output data of each row
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
}
I'm not really sure why this code doesn't work.

You will have to bind the result and below is the code - it is going to work please try it. please check if there any syntax issues in my code. otherwise it will work.
$value = (integer)$_GET["name"];
$sql = $dbConnection->prepare('SELECT 'coordinates', 'center' , 'content_string' FROM Regions WHERE `id` = ?');
$sql->bind_param('i', $value);
$sql->execute();
$sql->bind_result($coordinates, $center, $content_string)
while($sql->fetch())
{
echo $coordinates;
echo $center;
echo $content_string;
}

Prepared statement with MySQLi
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// prepare and bind
$stmt = $conn->prepare("INSERT INTO users (username, email) VALUES (?, ?)");
$stmt->bind_param("ss", $username, $email);
// set parameters and execute
$username= "John";
$email = "john#example.com";
$stmt->execute();
$username= "Mary";
$email = "mary#example.com";
$stmt->execute();
echo "New records created successfully";
$stmt->close();
$conn->close();
Php tips and tricks.
http://www.phptherightway.com/
If you are concerned about security this is the topic that I love very much.
What are the best PHP input sanitizing functions?.

Related

PHP: if statement testing if DB value equals a number - if true execute multiple sql query

Hello, I am trying to make php code that executes multiple sql queries as long as a certain database value equals 1. If that value does not equal one, then redirect the page to oops.php.
Here is my code so far:
<?php
session_start();
$servername = "localhost";
$username = "myUser";
$password = "myPass";
$dbname = "cashball_accounts";
$cash_amount = $_SESSION['cash_amount'];
// Create connection
$userid = $_SESSION['id'];
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Fetch the existing value of the cash_amount against that particular user here. You can use the SELECT cash_amount from users where userid = $userid
$_SESSION['cash_amount'] += $_POST['cashmade'];
$sql = "UPDATE users SET cashincheck = 0 WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $userid);
$result = $stmt->execute();
if($result)
{
echo "cashin complete!";
}
else
{
echo mysqli_error($conn);
session_start();
session_unset();
session_destroy();
}
$conn->close();
?>
So I want everything from the //Fetch comment to the if($result) to execute if the variable "cashincheck" is equal to 1 in the database.
For example:
if(SELECT cashincheck FROM users WHERE id = ? = 1) {
$_SESSION['cash_amount'] += $_POST['cashmade'];
$sql = "UPDATE users SET cashincheck = 0 WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $userid);
$result = $stmt->execute();
} else {
//redirect to oops.php
}
**/\ I know this wont work at all it's just an example /**
I also want to make several other if statements and update the database accordingly, meaning more sql queries and if statements will be needed,so how would I add more?
another example for a separate if statement:
if($_POST['cashmade'] < $_POST['type']) {
$sql = "UPDATE users SET moneymade = moneymade + $_POST['cashmade'] WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $userid);
$result = $stmt->execute();
} else {
$sql = "UPDATE users SET moneylost = moneylost + $_POST['type'] - $_POST['cashmade'] WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $userid);
$result = $stmt->execute();
}

mysql result into php array

I'm trying to convert the result that i'm getting from mysql to a php array
can anyone helps me
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "women";
$conn = new mysqli($servername, $username, $password, $dbname);
$id=$_GET['id'];
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT DAY(ADDDATE(`dateDebutC`, `dureeC`)) AS MONTHS,
DAY(ADDDATE(ADDDATE(`dateDebutC`, `dureeC`),`dureeR`))AS DAYS
FROM normalW
where id = '$id'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
foreach($new_array as $array){
echo $row['DAYS'].'<br />';
echo $row['MONTHS'].'<br />';
}
} else {
echo "0 results";
}
$conn->close();
?>
Problem solved Thank you guys
To answer your question you must first declare the new array
$new_array = array();
Then loop through your query results to populated the array
while ($row = $result->fetch()) {
$new_array[] = $row;
}
But as one of the comments mentioned you really should be using prepared statements to protect yourself from sql injection.
$stmt = $mysqli->prepare("SELECT DAY(ADDDATE(`dateDebutC`, `dureeC`)) AS MONTHS, DAY(ADDDATE(ADDDATE(`dateDebutC`, `dureeC`),`dureeR`)) AS DAYS FROM normalW where id = ?");
/* bind parameters i means integer type */
$stmt->bind_param("i", $id);
$stmt->execute();
$new_array = array();
while($row = $stmt->fetch()) {
$new_array[] = $row;
}

how to replace current_date() to any date type by user

how to replace current_date() to any date type by user
example:
www.example.com/2025-01-04
or any date
<?php
$servername = "localhost";
$username = "11_11";
$password = "1Eh]V";
$dbname = "1_1";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT domain FROM insights_base WHERE domain_1 = current_date() ";
$result = $conn->query($sql);
$data = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
}
$conn->close();
$smarty = new Smarty;
$smarty->assign('data', $data);
$smarty->display(APP_THEME . '/dom.tpl');
Try this:
<?php
$servername = "localhost";
$username = "11_11";
$password = "1Eh]V";
$dbname = "1_1";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_GET['date'])
and preg_match('/^\d{4}(-\d{2}){2}$/', $_GET['date']) // primitive validation
) {
$date = $_GET['date'];
} else {
$date = date('Y-m-d');
}
$sql = "SELECT domain FROM insights_base WHERE domain_1 = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $date);
$stmt->execute();
$stmt->bind_result($domain);
$data = array();
while ($stmt->fetch()) {
$data[] = array('domain' => $domain);
}
$conn->close();
$smarty = new Smarty;
$smarty->assign('data', $data);
$smarty->display(APP_THEME . '/dom.tpl');
I would recommend using a prepared statement here (assuming you are using mysqli).
A) Because you can dynamically assign either current_date() or variable using user input value to a placeholder.
B) The prepared statement would make this operation more secure since you are escaping all user input.
if (!empty($_POST['date'])) {
$user_date = $_POST['date'];
} else {
$user_date = "current_date()";
}
$sql = "SELECT domain FROM insights_base WHERE domain_1 = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $user_date);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$data = [];
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
}
Depending on how you are getting the date from user, you may need to validate it to make sure that it is in the proper date/time format for mysql.

slim framework no output displayed

I'm trying to get a json file using Slim Framework. The code I'm trying is mentioned below
$app->get('/forum/:id', function ($id) {
$user_name = "abc";
$password = "123";
$database = "test";
$server = "localhost";
$db_handle = mysqli_connect($server, $user_name, $password);
mysqli_set_charset($db_handle, "utf8");
mysqli_select_db($db_handle, $database);
$arr = array();
$SQL = "Select y123_forum.post_id, y123_forum.posttext FROM y123_forum INNER JOIN y123_users ON y123_forum.user_id = y123_users.id WHERE type = 1 AND y123_users.email = 'id'";
$result = mysqli_query($db_handle, $SQL);
while ($row = mysqli_fetch_assoc($result))
{
array_push($arr, $row);
}
mysqli_close($db_handle);
echo json_encode($arr);
});
The output displayed on the browser is []
When I try the above code without passing parameter, i.e
$app->get('/faqs/', function () {
$user_name = "abc";
$password = "123";
$database = "test";
$server = "localhost";
$db_handle = mysqli_connect($server, $user_name, $password);
mysqli_set_charset($db_handle, "utf8");
mysqli_select_db($db_handle, $database);
$arr = array();
$SQL = Select y123_forum.post_id, y123_forum.posttext FROM y123_forum INNER JOIN y123_users ON y123_forum.user_id = y123_users.id WHERE type = 1 AND y123_users.email = 'abc#gmail.com'"
$result = mysqli_query($db_handle, $SQL);
while ($row = mysqli_fetch_assoc($result))
{
array_push($arr, $row);
}
mysqli_close($db_handle);
echo json_encode($arr);
});
then it works fine
How do i fix this, I need to get this working to get the json file by passing any email id's from the database
You're forgetting the $ in the parameter, it thinks you're looking for an email address of 'id', not the contents of $id.
SELECT * FROM y123_forum WHERE email = '$id';
Note that this is a horrible, bad, unsafe way to pass parameters to a SQL query. The correct way would be to parameterize your query and execute this way:
$SQL = 'SELECT * FROM y123_forum WHERE email = ?';
$stmt = mysqli_stmt_init($db_handle);
if (mysqli_stmt_prepare($stmt, $sql)) {
mysqli_stmt_bind_param($stmt, 's', $id);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_assoc($result))
{
array_push($arr, $row);
}
}
The 's' in mysql_stmt_bind_param tells the driver your $id variable should be treated as a string, and escapes it appropriately.

MySql PHP Update Error

I've been messing about with this code for a few hours now and can't work out why it's not working. It's a profile update php page that is passed through JQuery and all seems to be fine except for it actually updating into the table. Here is the code I'm using:
session_start();
include("db-connect.php");//Contains $con
$get_user_sql = "SELECT * FROM members WHERE username = '$user_username'";
$get_user_res = mysqli_query($con, $get_user_sql);
while($user = mysqli_fetch_array($get_user_res)){
$user_id = $user['id'];
}
$name = mysqli_real_escape_string($con, $_REQUEST["name"]);
$location = mysqli_real_escape_string($con, $_REQUEST["location"]);
$about = mysqli_real_escape_string($con, $_REQUEST["about"]);
$insert_member_sql = "UPDATE profile_members SET id = '$user_id', names = '$name', location = '$location', about = '$about' WHERE id = '$user_id'";
$insert_member_res = mysqli_query($con, $insert_member_sql) or die(mysqli_error($con));
if(mysqli_affected_rows($con)>0){
echo "1";
}else{
echo "0";
}
All I get as the return value is 0, can anybody spot any potential mistakes? Thanks
To begin with, use
require("db-connect.php");
instead of
include("db-connect.php");
And now, consider using prepared statements, your code is vulnerable to sql injections.
Consider using PDO instead of the mysql syntax, in the long run I find it much better to use and it avoids a lot of non-sense-making problems, you can do it like this (You can keep it in the db-connect file if you want, and even make the database conncetion become global):
// Usage: $db = connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword);
// Pre: $dbHost is the database hostname,
// $dbName is the name of the database itself,
// $dbUsername is the username to access the database,
// $dbPassword is the password for the user of the database.
// Post: $db is an PDO connection to the database, based on the input parameters.
function connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword)
{
try
{
return new PDO("mysql:host=$dbHost;dbname=$dbName;charset=UTF-8", $dbUsername, $dbPassword);
}
catch(PDOException $PDOexception)
{
exit("<p>An error ocurred: Can't connect to database. </p><p>More preciesly: ". $PDOexception->getMessage(). "</p>");
}
}
And then init the variables:
$host = 'localhost';
$user = 'root';
$databaseName = 'databaseName';
$pass = '';
Now you can access your database via
$db = connectToDatabase($host, $databaseName, $user, $pass);
Now, here's how you can solve your problem (Using prepared statements, avoiding sql injection):
function userId($db, $user_username)
{
$query = "SELECT * FROM members WHERE username = :username;";
$statement = $db->prepare($query); // Prepare the query.
$statement->execute(array(
':username' => $user_username
));
$result = $statement->fetch(PDO::FETCH_ASSOC);
if($result)
{
return $result['user_id'];
}
return false
}
function updateProfile($db, $userId, $name, $location, $about)
{
$query = "UPDATE profile_members SET name = :name, location = :location, about = :about WHERE id = :userId;";
$statement = $db->prepare($query); // Prepare the query.
$result = $statement->execute(array(
':userId' => $userId,
':name' => $name,
':location' => $location,
':about' => $about
));
if($result)
{
return true;
}
return false
}
$userId = userId($db, $user_username); // Consider if it is not false.
$name = $_REQUEST["name"];
$location = $_REQUEST["location"];
$about = $_REQUEST["about"];
$updated = updateProfile($db, $userId, $name, $location, $about);
You should check the queries though, I fixed them a little bit but not 100% sure if they work.
You can easily make another function which inserts into tha database, instead of updating it, or keeping it in the same function; if you find an existance of the entry, then you insert it, otherwise you update it.

Categories