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

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.

Related

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'];

Android PHP MySQL Update - script works (db updated), but it throws error back to Android

Took the plunge into Android development (mostly for fun). I do have programming experience but not in Java.
Working on an activity where the user is pre-assigned a password they have to change when they first login. I basically duplicated the Login PHP and tweaked it to do an update (instead of checking for a valid username/pw). The php returns an error BUT, the password is actually updated in the database. Which does me no good since Android thinks there was an error.
Here's my PHP:
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$username = $_POST['username'];
$password = $_POST['password'];
$con=mysqli_connect(“server”,”user”,”pw”,”db”);
$sql ="UPDATE coaches SET coach_pw = '$password' WHERE (((coach_id)='$username'))";
$check = mysqli_query(mysqli_query($con,$sql));
if(isset($check)){
echo "success";
}else{
echo "Invalid Username or Password";
}
}else{
echo "error try again";
}
?>
The error I get back from PHP (from AS debug): html markup & "PHP Error Message" & html markup.
The last thing I changed that I thought was the problem was the mysqli_ function I was using (_fetch_array instead of _query). But that didn't fix the issue.
Any guidance will be greatly appreciated!
Well as Bang said in his comment, the double use of the mysqli_query function explains why the script returns an error.
Your query is correctly executed by the inner mysqli_query(), wich returns TRUE. This return value is then executed by the outer mysqli_query() wich, of course, returns an error.
That is why the query is successfully executed but an error is sent.

MYSQLI_NUM_ROWS THROWS SERVER ERROR

Can someone please explain to me why I keep getting the following error when I use the mysqli_num_rows() function?
Internal Server Error
The server encountered an internal error or misconfiguration and was unable to complete your request.
Please contact the server administrator to inform of the time the error occurred and of anything you might have done that may have caused the error.
More information about this error may be available in the server error log.
Here is my php script:
<?php
//stores user input as variable
$username = $_POST['username'];
$password = $_POST['password'];
//selects from users table
$sql = "SELECT * FROM Members WHERE username='$username' and password='$password'";
$results = mysqli_query($con,$sql);
$count = mysqli_num_rows($results);
/*//starts session and sets cookie if count is true
if($count>=1)
{
session_start();
$_SESSION['username'] = ' ';
$_SESSION['password'] = ' ';
header("location: index.html");
}
//returns message if user input does not match database
else
{
echo "Invalid username or password";
}*/
?>
I get this error at the mysqli_num_rows() function everything before it works fine. I am using Plesk on a Godaddy server by the way.
You need to learn how to read php and mysqli errors
You need to learn how to use mysqli properly
You don't heed this function at all
How to get mysqli error in different environments? for the first
and How can I prevent SQL injection in PHP? for the second
just fetch your data and use it as a flag for the last
As far as I can see there is no function as mysqli_num_rows().
Is the $con variable declared elsewhere? I don't see it being declared. Also, you are subject to injection attacks with this current code. Make sure you escape your parameters before using this publicly.

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

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.

Why is this database error occuring?

I am using the JQuery .post method to get data using an AJAX call. The PHP file that is rendering the data has the following code that inputs information into a database:
$query = "INSERT INTO questions(question, added_by) VALUES ('$question', '$user_id')";
$result = mysql_result($query);
//If db error
if(!$result )
{
$error = str_replace("'", "*", mysql_error());
$method = __METHOD__.'line: '.__LINE__;
return Error::db_error($method, $error, $this->ip, 'An internal error has occurred. Your question can not be added at this time.');
}
According to this code, a database error is occurring, yet mysql_error() is blank. When I use die($query), and copy and paste the literal query string into my mysql gui window (sqlyog) and run the query, it inserts just fine with no warnings or errors.
I have this general set-up for some other PHP functions and it works just fine.
I am really stumped by this. Any help would be greatly appreciated. Thanks.
Execute the query using mysql_query before Retrieving the contents of cells from a MySQL result set using mysql_result.
$result = mysql_query($query);
echo mysql_result($result);
Could it be an encoding issue? What is your contentType on the Ajax post?

Categories