Using a variable (not user inputted) in an SQL query - php

I am trying to encode json for several fields of different tables in my database. Below is my code. I am currently using an array to represent the names of my tables ($tablename). I've read about SQL injections but they seem to focus specifically on user input. However, in this case there is no user interaction with my database. It's a backend for my app. Any thoughts on using variable names like this? Thanks
I also looked into prepare statements but it was quite difficult to fetch the data in the form i wanted.
<?php
include $_SERVER['DOCUMENT_ROOT'] . '/mmcv/buildchartInfo.php';
$position = 0;
$results = array();
foreach($chartnames as $tablename) {
print $tablename."<br />";
encodejson($tablename);
}
function encodejson($tablename){
include $_SERVER['DOCUMENT_ROOT'] . '/mmcv/includes/connect.inc.php';
$sql="SELECT rank, name FROM $tablename";
$result = mysqli_query($connection,$sql);
//Error when data isn't returned
if(!$result)
{
$output = "error getting data";
echo $output;
//$GLOBALS['loginError'] = "error getting log in data";
exit();
}
while($row=mysqli_fetch_assoc($result)) $output[]=$row;
print(json_encode($output));
}
mysqli_close($connection);
?>

As long as the user can't change the value of $tablename, then you have nothing to be scared about.

As a general rule I'd suggest you to always use prepared statements even without user input. But technically speaking if you are absolutely sure the variable $tablename cannot be modified directly or indirectly (doesn't depends from other user inputted variables) then I guess it's fine to go with that.
Notice: table names cannot be prepared (SELECT ... FROM :table WHERE ... will not work), therefore sometimes you can't choose.
But sometimes its hard to track the real dependencies of a variable, therefore I still highly suggest you to with prepared statements.

Related

Best way to approach sending external php a variable

I was wondering if some one could direct me on the right path to take because every way I have tried has failed or really broken my code. To keep it simple I have page with a dynamically created select box populated with peoples names from a mySQL database its element id is 'insert'. This page also holds the php query
my query on the database works if I hard code a name in but I want to pass it as a variable from the select box. I can't seem to get it to post my variable and return me an id.
heres my query
<?php
function getElementById($id) {
$xpath = new DOMXPath(NEW domDocument);
return $xpath - > query("//*[#id='$id']") - > item(0);
}
$insertName = getElementById('insert');
printf($insertName);
$con = mysqli_connect("localhost", "root", "", "karaoke");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: ".mysqli_connect_error();
}
$sql = "Select id FROM queue where singer = '$insertName'";
$result = mysqli_query($con, $sql) or die("Bad SQL: $sql");
while ($row = mysqli_fetch_assoc($result)) {
$insertAt = ("{$row['id']}");
printf($insertName);
printf($insertAt);
};
?>
whats the best way to get my variable sent to the script and then return me the answer.
thanks
You can use either the POST or GET form methods to send data from your HTML form to your PHP script. In the form element, you will want to set the action to your PHP script like so: <form action = 'your_php_file.php' method = 'GET or POST'>. This means that when the form is submitted, you can get the data from this PHP file. Then, in your PHP, you will want to use the global variable for either POST or GET (depending on which you have used for the form method) to get the value from the select box. Using this method means you can replace your GetById function and assign the value from the form to the $insertName variable using the superglobals.
Another problem in your code is that you use your PHP variables in your SQL query. This means that your code is open to an SQL injection which could lead to problems such as people getting all of the database info (which is bad for a database storing poorly encrypted/hashed passwords, or even storing them in plain text)or could even lead to your database being deleted. To avoid this, you should use prepared statements and parameters whereby the statement is sent first without the variable and the variable is bound after.
Also, take a look at the links above about POST and GET and also about the PHP global variables which will allow you to get the data from your HTML form. Also, here are some links which explain prepared statements and parameters so that you can write more secure PHP code:
Mysqli prepare statement used to prepare the statement. The use of question marks are as placeholders as you later bind your variables to the query.
Mysqli Bind Param used to add in the variable to the SQL statement after the statement has been prepared which prevents SQL injection.
That's all for now, but be sure to ask any questions you may have and I will try my best to answer them all.
EDIT
ADDED CODE - hopefully will demonstrate what you were after, there are some small changes that may need to be made. There may be some extra code needed to fit in with any other code you have, but this should demonstrate the principle of POST and prepared statements with parameters. Written in OOP as opposed to your procedural as I find it cleaner and easier (personal opinion). If there are any problems integrating this be sure to tell me about any errors or issues/further questions. I too am fairly new to PHP.
<?php
$insertName = $_POST['insert']; // Get the value of the select box which will need to have the attribute 'name = "insert"' by POST
printf($insertName);
$con = new mysqli("localhost", "root", "", "karaoke");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: ".mysqli_connect_error();
}
$sql = "Select id FROM queue where singer = ?";
$stmt = $con->prepare($sql);
$stmt->bind_param("s", $insertName); //Binds the string insertName to the question mark in the query
$stmt->execute();
while ($row = $stmt->fetch_assoc()) { // Left as was because syntax is different from PDO which I use. Therefore, I am assuming this part is correct.
$insertAt = ("{$row['id']}");
printf($insertName);
printf($insertAt);
};
?>

Php only takes in the first row of the database as correct credentials

This is the code for my log in forum. The problem with it is that it only accepts as correct credentials the first username and password (basically only the first row) any ideas as to how i could change it ?!
<?php
session_start();
include_once("connect.php");
$token = "";
if($con->connect_error){
die("Connection failed: ".$con->connect_error);
}
$sql = "SELECT * FROM authme";
$result = mysqli_query($con, $sql) or die(mysqli_error($con));
while(mysqli_num_rows($result)>0){
while($row = $result->fetch_assoc()){
if(isset($_POST['realname']))
$username = $_POST['realname'];
if($result->num_rows>1){
if(mysqli_num_rows($result)>1){
$_SESSION['uid'] = $row['id'];
$_SESSION['realname'] = $row['realname'];
}
$password = '$SHA$'.substr($row['password'],5,16).'$'.hash('sha256', hash('sha256',$_POST['password']).substr($row['password'],5,16));
if($password == $row['password'] ){
header("Location: index.php");
exit();
}
else {
echo "INVALID INFORMATION, PLEASE RETURN!";
// header("location: index.php");
session_destroy();
exit();
}
}
}
}
?>
?
I decided to try to make a log in forum that uses a database which encrypts the passwords it receives through a register form. This code only takes as correct the first username and password i give in and its not enough, as you could imagine.
Welcome to programming with PHP. I'm going to try to share a few principles that may help you solve your problem.
1.) One of the best features in PHP is the print_r() function. Using this function you can output almost anything to text in the browser. So in this case you may want to insert a print_r($result) immediately following this line "$result = mysqli_query($con, $sql) or die(mysqli_error($con));". This will output the results of the query that PHP is receiving. This can be used to help you troubleshoot and determine why your code isn't working. Once you're done troubleshooting delete that line.
2.) You seem to have multiple checks for the number of rows inside the while loop. I'm not sure why you have thoose there, but you may want to check if those are causing your trouble by using echo or print to display to values in the browser for troubleshooting. Once you're done troubleshooting delete that line.
3.) Another overall concept for the data you are querying. It is inefficient to send a query that gets the entire table and returns it to the program, that then loops through every row looking for the data. Instead you should write an SQL query to return only the row of data the you want. Make sure you do use prepared statements.
4.) Your coding standards could use some improvement, if you clearly tabbed your statements it would be easier to read. Consider reading PSR-2. For example this code seems to be missing {}'s.
if(isset($_POST['realname']))
$username = $_POST['realname'];

PHP Error Retrieving Data From Remote Database (Not Populating Query)

The following code takes data from a form to be retrieved from a remote database.
$find = mysqli_real_escape_string($connect, $_POST['name']);
echo ' '.$find;
$query_seek = mysqli_query($connect, "SELECT * FROM test_2 WHERE NAME = '$find' ");
if($query = $query_seek)
{
echo 'query successful';
}
When I run it, the query does not seem to resolve or echo any data. Could it be as simple as using a get method versus post? I prefer to not have the query pass through the URL for security but if can't be helped so be it. I assume the syntax for the SQL to be correct as I ran it on the server side through PHPMyAdmin's SQL client. Anything glaringly incorrect?
This block comes after a check where the input is verified for length and no white space.

Using php/pdo to display sql data on website, no luck

I know this is probably something simple, but I have searched for hours the past few days and I'm ready to jump out of my one-story building.
Have a basic site for testing, literally nothing on it but opening/closing html tags.
A very basic table in a data base, using phpmyadmin to access it.
Trying to get table contents to display on the basic website.
Was using mysqli_ or mysql_ style in the php to access the data for a while with no luck.. Have since been reading about PDO and found numerous tutorials on how to use it. I feel like what I'm trying to do should be so simple but I've tried copying what I've found on this site and other tutorials to the T and the site still does not display the data.
try {
$conn = new PDO("mysql:host=$hostname; dbname=$userdb", $username, $password);
$conn->exec("SET CHARACTER SET utf8");
$sql = "SELECT * FROM Monday";
$result = $conn->query($sql);
while($row = $result->fetchAll(PDO::FETCH_ASSOC)) {
echo $row['Name'] . '<br />';
}
$conn = null;
}
catch(PDOException $e) {
echo $e->getMessage();
}
Basically the website will display everything after the first -> in this case after the $conn-> but none of the actual table data.
I've tried about 50 different ways at least from numerous sites and I'm just lost now I guess..
Side note: I do have php forms on the same site that when submitted successfully insert data into the table, so I know I am able to connect to the db and table and INSERT, its just the issue of SELECT I can't get.
Thanks for any help
EDITED: to add fetchAll
You are using the method fetch() in your loop, which only fetches the next single row of your results. Replace it with fetchAll() and it should work.
More information about the fetchAll() method:
http://php.net/manual/en/pdostatement.fetchall.php
And for testing purposes you could set the PDO error mode to PDO::ERRMODE_EXCEPTION. See: http://php.net/manual/en/pdo.error-handling.php
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
Should be;
while($row = $result->fetchAll(PDO::FETCH_ASSOC)) {

sql in php not returning anything

How do I see what is returned from a sql statement in php? I have the following function to get user name from mysql database and I use echo in another php to see the result but nothing shown.
function get_user_name($id_user) {
return mysql_result(mysql_query("SELECT username FROM user WHERE id_user = '$id_user'"));
}
echo $id_user;
$a = get_user_name($id_user);
echo $a;
Can anyone help? Thanks.
Are you echoing the get_user_name(); function?? OR are you even connected to your database? these are two things you need to check before, (if the problem remains) including an error handling method i.e. or die(mysql_error()) at the end of your query to find out the problem.
return mysql_result(mysql_query("SELECT id_user FROM user WHERE id_user = '$id_user'")or die (mysql_error()));
The error handling construct?? in mysql mysql_error() should output the problem in fairly understandable way, as to what is preventing your query not to be shown

Categories