PHP Query failing, show error? - php

I have a query on my page that uses a GET variable to pull data from my table...
If I echo my GET var the data is there so im doing something wrong with my query, instead of or die can I show an error in the browser?
// Get USER ID of person
$userID = $_GET['userID'];
// Get persons
$sql = 'SELECT * FROM persons WHERE id = $userID';
$q = $conn->query($sql) or die('failed!');

$sql = "SELECT * FROM persons WHERE id = $userID";
You must use double quotes to use variables inside the query string.
You can also do this:
$sql = "SELECT * FROM persons WHERE id = ".$userID;
What you should do is this (to protect yourself from sql injection):
$safeuid = $conn->prepare($userID);
$sql = "SELECT * FROM persons WHERE id = ".$safeuid;
You can always debug using this at the top of your php page:
ini_set('display_errors',1);
error_reporting(E_ALL);

Have you tried $q = $conn->query($sql) or die($conn->error()); ?

Yes you can, but you should only do it for debugging. Crackers can gain a lot of insight by purposefully feeding bad input and reading the error.
I'm assuming you're using MySQLi; the command is $conn->error(). So your line would be:
$q = $conn->query($sql) or die($conn->error());
Also, what you're doing wrong is you're using single quotes to define $sql. You need to use double quotes to write $userID into the string. So what you want is:
$sql = "SELECT * FROM persons WHERE id = $userID";
or
$sql = 'SELECT * FROM persons WHERE id = ' . $userID;

You need to use double quotes to evaluate variables within the string. That is,
$sql = 'SELECT * FROM persons WHERE id = $userID';
should be
$sql = "SELECT * FROM persons WHERE id = $userID";
Rather than removing the die you should make sure the query is always valid. In other words: validate the userID parameter. $_GET can contain anything the user wants to provide - it could be an array, it could be a string, it could be a string with a malicious payload that can drop your tables. So check it is an integer. If not, return a relevant message to the user.

Not a php expert but you might try:
// Get USER ID of person
$userID = $_GET['userID'];
// Get persons
$sql = 'SELECT * FROM persons WHERE id = $userID';
$q = $conn->query($sql) or die('failed!' . mysql_error());
The error should append to the end of your die message.

Related

Turn SQL value to variable

so I have a database table with some user information, like ID, username, etc. and I have been trying to turn a value, for example, Bob's ID into a variable $id from the table. This is what I have right now:
$db = mysqli_connect(THIS WORKS FINE AND CONTAINS SECRET INFO :));
$sql = "SELECT ID FROM users WHERE username='$prompt'";
$result = mysqli_query($db, $sql);
and I need to turn it into a variable, because I am combining everything into a sentence so it could be $username has the id of $id. Thanks
Try like this.use sprintf().The sprintf() function writes a formatted string to a variable.
$db = mysqli_connect(THIS WORKS FINE AND CONTAINS SECRET INFO :));
$sql = "SELECT ID,username FROM users WHERE username='$prompt'";
$result = mysqli_query($db, $sql);
$row = mysqli_fetch_assoc($result);
$sentence = sprintf("%s has the id of %u.",$row['username'],$row['ID']);
echo $sentence;
For more see sprintf

Get subject from Table in PHP

OK So I'm trying to access a table called emg_quote I have the Quote ID so Im trying to get the Column Subject from the same row as this ID but for some reason All I'm getting is the first row in the entire table? Can any one figure out what I'm doing wrong? Here is my coding:
$row['quote_id'] = quoteTitle($row['quote_id']);
function quoteTitle($quoteid){
global $db;
$sql = "SELECT subject FROM emg_quote WHERE ".$quoteid."";
$res = $db->query($sql);
$row = $db->fetch_row();
$output = $row['subject'];
return $output;
}
Are you using a custom object to wrap the native API's?
Either way it doesn't look right to me. You don't seem to be using the result of the query.
i.e.
$result = $mysqli->query($query);
$row = $result->fetch_row();
You have few bad practices in your code.
A. You lie on $quoteid to give you the correct where syntax. ie: ID=123
This is an highly unsafe method, because the user can change the it to Some-Important-Details='bla'
To extract more details from this table or others.
B. You should ALWAYS escape characters when receiving data from user, otherwise you easily subjected to SQL-Injections. And believe me you don't want it.
you have to use the checking after where.
use you column name before your $quoteid variable
$row['quote_id'] = quoteTitle($row['quote_id']);
function quoteTitle($quoteid){
global $db;
$sql = "SELECT subject FROM emg_quote WHERE quoteid=".$quoteid." LIMIT 1 ";
$res = $db->query($sql);
$row = $db->fetch_row();
$output = $row['subject'];
return $output;
}
Remember : USE limit 1 when you search with primary key and you know that only 1 record will be searched. it reduce your processing time.
You might be missing the where column.
$sql = "SELECT subject FROM emg_quote WHERE quote_id=".$quoteid."";
^^^^^^^^
We also do not see weather something with your Db class is wrong.
You should in any case not directly put request variables into a database query.
$sql = "SELECT subject FROM emg_quote WHERE ID='".$quoteid."'";
You had not wrote your db fieldname in where condition

PHP error get value from database

I have php script like this
$query = "select * where userid = 'agusza' ";
$result = mysql_query($query) or die(mysql_error());
while($row=mysql_fetch_array($result)) {
echo $result;
}
when I execute, the result like this
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'where userid = 'agusza'' at line 1
But when I run that sql in sqlserver, it running well
Anybody has solution ?
$query = "select * from table_name where userid = 'agusza' ";
See the corrections I have made. You haven't used the right syntax for SELECT query
You didn't select a table using FROM. Without that, it does not know which table you are selecting data from.
You should also stop using mysql as it is deprecated. Use mysqli or PDO as they are safer.
You are also echoing the wrong variable in your while loop, try this:
while ($row = mysql_fetch_array($result) {
echo $row['column_name'];
}
$query = "select * from table where userid = 'agusza'";
Right now, you're not telling which table SQL should look in.
You should format your query like so:
select * from `TableName` where userid='agusza'
In your query below you doesnt state the database table where you should get that data using FROM
$query = "select * where userid = 'agusza' "; // instead of this
$query = "select * FROM declaredtable where userid = 'agusza' "; used this

What is the proper syntax for inserting variables into a SELECT statement?

I believe I have a simple syntax problem in my SQL statement. If I run this code, I get an error in the database query.
$user = $_GET['linevar'];
echo $user; // testing - url variable echos correctly
$sql = "SELECT * FROM `userAccounts` WHERE `name` = $user";
$result = mysql_query($sql) or die("Error in db query");
If I replace $user in the $sql string with 'actualName' or a known record in my table, the code works fine. Am I using the $ variable incorrectly in the SQL string?
You need to surround the value that you're getting from $user with quotes, since it's probably not a number:
$sql = "SELECT * FROM `userAccounts` WHERE `name` = '$user'";
Just as a note, you should also read up on SQL injection, since this code is susceptible to it. A fix would be to pass it through mysql_real_escape_string():
$user = mysql_real_escape_string( $_GET['linevar']);
You can also replace your or die(); logic with something a bit more informative to get an error message when something bad happens, like:
or die("Error in db query" . mysql_error());
You need escape the get input, then quote it.
// this is important to prevent sql injection.
$user = mysql_real_escape_string($_GET['linevar']);
$sql = "SELECT * FROM `userAccounts` WHERE `name` = '$user'";
This should work:
$sql = "SELECT * FROM `userAccounts` WHERE `name` = '" . $user . "'";

MySQL Select statement

I have 2 values that I'm suppling my script - I want to search for any one of those datas. How do I write my query like this:
SELECT * FROM table WHERE id = '".$id."' or "name='".$name."';
my problem is escaping the quotes in the query.
Any help will be appreciated.
There are a few ways to do it, a lot of them frowned on but generally I would stick to using MySQLi and using the
mysqli_real_escape_string($id)
function or in OOP
$mysqli = new mysqli('host', 'user', 'pass', 'database');
$id = $mysqli -> real_escape_string($id);
$name = $mysqli -> real_escape_string($name);
$results = $mysqli -> query("SELECT * FROM table WHERE id = '{$id}' or "name='{$name}'");
You may use curly brackets to avoid confusion with escaping characters as follows:
$query = "SELECT * FROM table WHERE id = '{$id}' or name = '{$name}' ";
You may also consider using wildcards such as %$letter% to search for word anywhere in the name field as:
$query = "SELECT * FROM table WHERE id = '{$id}' or name LIKE '%{$name}%' ";
SUGGESTTION:
You should always use id fields as integer for better performance.
Use this fancy function, mayhaps? The examples have what you're looking for.
You've got an extra quote; if you want to stick with your original code (not recommended), try something like this:
$query = "SELECT * FROM table WHERE id = '".$id."' or name='".$name."'";
But really you should be using parameterised queries so that you avoid possible SQL injection security issues!
Write it as:
$name = mysql_real_escape_string($name);
$id = mysql_real_escape_string($id);
$query = "SELECT * FROM table WHERE id = '$id' or name= '$name' ";
Because you started with double quotes the single quotes are part of the query and the $vars are expanded.

Categories