MYSQL assign column name to variable? - php

I have a database table which has two columns, business and tourist.
I ask a user to select one of them from dropdown list, then use the result in a SELECT statement in MySQL. I assign this column to $cclass, then I make this statement SELECT $cclass FROM flights ....
But it always returns NULL. Why does it return NULL and how do I fix this?
My code:
$check = mysql_query("SELECT $cclass FROM flights WHERE flight_no = '$flightno'");
while ($result = mysql_fetch_assoc($check))
{
$db_seats = $result['$cclass'];
}

you should replace this line:
$db_seats = $result['$cclass'];
with this:
$db_seats = $result[$cclass];
string between 2 single quotes doesn't parsed:
Strings

Have you tried doing the following:
$check = mysql_query("SELECT".$cclass." FROM flights WHERE flight_no = '$flightno'");

First of all, this code has a serious security issue, as it is vulnerable to SQL Injection. You should be using the MySQLi extension instead, and properly filtering your input.
Try something like this:
<?php
/* Create the connection. */
$mysql = new mysqli("localhost", "username", "password", "myDB");
if ($mysql->connect_error)
{
error_log("Connection failed: " . $mysql->connect_error);
die("Connection failed: " . $mysql->connect_error);
}
/* Sanitize user input. */
if (!in_array($cclass, array('business', 'tourist')))
{
error_log("Invalid input: Must be 'business' or 'tourist'");
die("Invalid input: Must be 'business' or 'tourist'");
}
$statement = $mysql->stmt_init();
$statement->prepare("SELECT $cclass FROM flights WHERE flight_no = ?");
$statement->bind_param("s", $flightno);
if (!$statement->execute())
{
error_log("Query failed: " . $statement->error);
die("Query failed: " . $statement->error);
}
if ($statement->num_rows < 1)
{
echo "No results found.";
}
else
{
$statement->bind_result($seats);
while ($statement->fetch())
{
echo "Result: $seats";
// Continue to process the data... You can just use $seats.
}
}
$mysql->close();
However, the reason your original example is failing, is that you're quoting $cclass:
$db_seats = $result[$cclass];
However, please do not ignore the serious security risks noted above.

Related

PHP Delete From Table Via Form Issue

I'm working on a very basic PHP programme. I'm very new to PHP and am aware that I'm using the older versions i.e not PDO. I've been working on this for a while and can't figure out why it isn't working.
I'm simply trying to delete an item from my table which matches the user input.
((also if anyone has any easy recommendations I can use to have a safer delete function as I am aware if the user input is 'r' for example, a huge chunk of the table will be deleted))
Here is my code:
<?php
//delete from table
if(isset($_POST['delete1']))
{
$deletevalue = $_POST['deletevalue'];
$deletequery = "DELETE FROM users WHERE deletevalue = $deletevalue";
$deleteresult = deleteTable($deletevalue);
}
function deleteTable ($deletevalue)
{
$connect = mysqli_connect("localhost", "root", "", "test_db");
$delete_fromTable = mysqli_query($connect, $deletevalue);
print mysqli_error($connect);
}
?>
<!DOCTYPE html>
<html>
<body>
<form action="zzz.php" method="post" />
<p> Remove Item: <input type="text" name="deletevalue" placeholder="Item
Name" /> </p>
<input type="submit" name ="delete1" value="submit" />
</form>
</body>
</html>
regarding all comments, and completely OK with security statements, you should really consider using PPS : Prepared Parameterized Statements. This will help Preventing SQL injection. Plus : use error_reporting(E_ALL); ini_set('display_errors', 1); on top of your pages will help PHP give you hint about errors :)
This is a way (not the only one) to handle your query.
Please read carefully and adapt names according to your DB structure and column names.
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
$host = ""; /* your credentials here */
$user = ""; /* your credentials here */
$pwd = ""; /* your credentials here */
$db = ""; /* your credentials here */
/* store in PHP variable */
$deletevalue = $_POST['deletevalue'];
echo"[ is my var ok ? -> $deletevalue ]"; /* just checking value */
// connexion to db
$mysqli = mysqli_connect("$host", "$user", "$pwd", "$db");
if (mysqli_connect_errno()) { echo "Error: no connexion allowed : " . mysqli_connect_error($mysqli); }
$query = " DELETE FROM `users` WHERE deletevalue = ? ";
$stmt = $mysqli->prepare($query); /* prepare query */
$stmt->bind_param("s", $deletevalue); /* bind param will sanitize -> 's' is for a string */
print_r($stmt->error_list); /* any error ? */
print_r($stmt->get_warnings()); /* any error ? */
print_r($stmt->error); /* any error ? */
/* another ways of checking for errors :
if (!($stmt = $mysqli->prepare(" DELETE FROM `users` WHERE deletevalue = ? "))) {
echo "Error attempting to prepare : (" . $mysqli->errno . ") " . $mysqli->error;
}
if (!$stmt->bind_param("s", $deletevalue)) {
echo "Error attempting to bind params : (" . $stmt->errno . ") " . $stmt->error;
}
*/
if (!$stmt->execute()) { echo"false"; echo "Error attempting to execute : (" . $stmt->errno . ") " . $stmt->error; } else { echo"true"; }
?>
Here your code will be looks like (Except security issue)
In this code you are deleting your record on the basis of firstName of the user thats why in where clause WHERE firstName = '$deletevalue' firtName there.
if(isset($_POST['delete1']))
{
$deletevalue = $_POST['deletevalue'];
//here put your table column in where clause
$deletequery = "DELETE FROM users WHERE firstName = '$deletevalue'"; //if your form enters name of the users
$deleteresult = deleteTable($deletequery);
}
function deleteTable ($deletequery)
{
$connect = mysqli_connect("localhost", "root", "", "test_db");
$delete_fromTable = mysqli_query($connect, $deletequery);
print mysqli_error($connect);
}
See in your where clause WHERE name = if you are deleting on the basis of name of the user.
and also see deleteTable($deletequery); you need to pass your query not the value.
Note:
Yes, I know you are learning basic things but my recomendations are
1) Use Prepared statements, explore little bit about it
2) Delete records based on ID (unique field) not name, name (firstName) might be same for multiple users in users table

Checking to see if ID is already in database, if it is don't INSERT it again

When I run the page with an empty database, it will insert the data correctly. When I run the page again, it displays there is already an ID in the database, but it inserts it anyway. Not sure how or why but I've tried every combination of booleans inside the if statements and cant get it to chooch correctly.
//pass in an ID to compare:
function checkOrderID($orderID) {
//Connect to the database:
$mysqli = new mysqli("localhost", "root", "", "price");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//Ask the database for some sweet, sweet data:
$stmt1 = "SELECT orderID FROM orders";
$result = $mysqli->query($stmt1);
//flag (we want to believe that there are no similar IDS so lets make it true):
$flag = true;
//while we got some data, display that shit
while ($row = $result->fetch_assoc()) {
//asign data to variable:
$rowOrderID = $row['orderID'];
//Does it match? if it does set the flag to false so it doesnt get inserted.
if ($rowOrderID == $orderID) {
echo "Row ID" . $row["orderID"] . " Passed ID: " . $orderID . "<br>";
echo "This order is already in the database" . "<br>";
$flag = false;
}
}
//hand the flag over to who ever needs it
return flag;
}
.
if (checkOrderID($orderID) == true) {
//some mysql insert logic here
}
Why are you making this complicated. just do something like this:
$con=mysqli_connect("localhost","root","","price");
$check_query = mysqli_query($con,"SELECT * FROM orders WHERE orderID = $orderID");
if (mysqli_num_rows($check_query) == 0) {
//mysql insert logic here
}
(Noted of course you are going to have your connection logic as well)
Note: You are using Mysqli in object oriented manner but in this example i have not used object oriented manner of DB connection. The connection variable $con must be passed to mysqli_query() method.
Also... random side note, but it's generally a good idea to have a password for your root mysql user.
Here better and short, but please try to use DB connection globally not inside your mothod and try to use prepared statements. But except those you can use following code.
//pass in an ID to compare:
function checkOrderID($orderID) {
//Connect to the database: I suggest use global DB connection
$mysqli = new mysqli("localhost", "root", "", "price");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//gets recodrs based on $orderID passed to this method
$stmt1 = "SELECT * FROM orders where orderID=$orderID"; //Try to use prepared statement
$result = $mysqli->query($stmt1);
//Store number of rows found
$row_count = $result->num_rows;
if($row_count>0){
return true;
}
else{
return false;
}
}

How can I check for duplicate usernames using PHP and MySQL?

I'm just learning PHP and I thought it would be a good idea to learn some MySQL too.So I started working on the code and for some strange reason I keep getting duplicate users which is really really bad.
<?php
$link = mysqli_connect(here i put the data);
if(!$link)
{
echo "Error: " . mysqli_connect_errno() . PHP_EOL;
exit;
}
else
{
if(isset($_POST['user']))
{ echo "User set! "; }
else { echo "User not set!"; exit; }
if(isset($_POST['pass']) && !empty($_POST['pass']))
{ echo "Password set! "; }
else { echo "Password not set!"; exit; }
$num = mysqli_num_rows(mysqli_query("SELECT * FROM `users` WHERE ( username = "."'".$_POST['user']."' )"));
if($num > 0)
{ echo "Cannot add duplicate user!"; }
mysqli_close($link);
}
?>
For some strange reason I don't get the output I should get.I've tried some solutions found here on StackOverflow but they didn't work.
The first parameter of connectionObject is not given in mysqli_query:
$num = mysqli_num_rows(mysqli_query($link, "SELECT * FROM `users` WHERE ( `username` = '".$_POST['user']."' )"));
//----------------------------------^^^^^^^
Also, your code is vulnerable to SQL Injection. A simple fix would be:
$_POST['user'] = mysqli_real_escape_string($link, $_POST['user']);
mysqli_query must receive two parameters in order to work. In this case, your mysqli_connect.
$num = mysqli_num_rows(mysqli_query($link, "SELECT * FROM `users` WHERE ( username = "."'".$_POST['user']."' )"));
Also, you can be affected by SQL Injection, in this code.
Never add user input directly in your queries without filtering them.
Do that to make your query more readable and safe:
$u_name=mysqli_real_escape_string($link, $_POST['user']);
$num = mysqli_num_rows(mysqli_query($link, "SELECT * FROM `users` WHERE ( username = '$u_name' )"));
To use mysqli_* extension, you must include your connection inside of the parameters of all queries.
$query = mysqli_query($link, ...); // notice using the "link" variable before calling the query
$num = mysqli_num_rows($query);
Alternatively, what you could do is create a query() function within your website, like so:
$link = mysqli_connect(...);
function query($sql){
return mysqli_query($link, $sql);
}
and then call it like so:
query("SELECT * FROM...");
This could be a problem of race condition.
Imagine that two users wants to create the same username at the same time.
Two processes will execute your script. So both scripts select from database and find out that there is not an user with required username. Then, both insert the username.
Best solution is to create unique index on username column in the database.
ALTER TABLE users ADD unique index username_uix (username);
Then try insert the user and if it fails, you know the username exists ...
Here's how to write your code using prepared statements and error checking.
Also uses a SELECT COUNT(*)... to find the number of users instead of relying on mysqli_num_rows. That'll return less data from the database and just seems cleaner imo.
<?php
$link = mysqli_connect(here i put the data);
if(!$link) {
echo "Error: " . mysqli_connect_errno() . PHP_EOL;
exit;
}
else if(!isset($_POST['user'])) {
echo "User not set!"; exit;
}
echo "User set! ";
if(!isset($_POST['pass']) || empty($_POST['pass'])) {
echo "Password not set!"; exit;
}
echo "Password set! ";
$query = "SELECT COUNT(username)
FROM users
WHERE username = ?";
if (!($stmt = $mysqli->prepare($query))) {
echo "Prepare failed: (" . mysqli_errno($link) . ") " . mysqli_error($link);
mysqli_close($link);
exit;
}
$user = $_POST ['user'];
$pass = $_POST ['pass'];
if(!mysqli_stmt_bind_param($stmt, 's', $user)) {
echo "Execute failed: (" . mysqli_stmt_errno($stmt) . ") " . mysqli_stmt_error($stmt);
mysqli_stmt_close($stmt);
mysqli_close($link);
exit;
}
if (!mysqli_execute($stmt)) {
echo "Execute failed: (" . mysqli_stmt_errno($stmt) . ") " . mysqli_stmt_error($stmt);
mysqli_stmt_close($stmt);
mysqli_close($link);
exit;
}
$result = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_array($result, MYSQLI_NUM)) {
$num = $row[0];
if($num > 0) {
echo "Cannot add duplicate user!";
}
}
mysqli_stmt_close($stmt);
mysqli_close($link);
please do suggest fixes to syntax, this was typed from a phone

How to work with data from mysql in php-multidimensional array

I get null values when I run this code
$dataArray = mysql_query ("SELECT * from _$symbol order by date DESC limit 10;");
while ($ArrayData = mysql_fetch_assoc($dataArray)) {
$dayData [] = $ArrayData;
}
$todaysdate = $dayData[0]['date'];
$volPercentAVG = $dayData[0]['volume'] / $dayData[0]['_50dayVol'];
mysql_query ("update _$symbol set volPercentAvg=$volPercentAVG WHERE date=$todaysdate;");
It does not return anything, I am not sure I am approaching the MDarray correctly? I have triple checked the column names.
Anywhere to do with this would be helpfull
Thanks.
#Fred-ii- YOU DID IT! Can I or you make this an answer so I can vote for it? If I can I dont see how. – illcrx
Posting my comment as the answer in order to close the question.
If your date column contains any spaces or dots etc. then change WHERE date=$todaysdate
to/and quoting it WHERE date='$todaysdate'
For example: 2014-10-06 22:59:52
Would explain why you were not getting results.
However, I'm quite surprised/baffled that MySQL did not throw you a syntax error, bizarro.
Don't have time to read your entire bit right now, but I can give you my test method from our standard mysqli execution set:
print_r($Record);
This will allow you to see the structure and possibly where your error lies.
I'll also give you our framework which can be very useful (which is why we have it! LOL). Example framework (two functions) to make it easier to use mysqli in php with two lines for each query. It also allows for CLI or web output and debugging which will dump the query (so you can run it) and shows a print_r function to show results.:
This goes at the top:
define('DEBUG', false);
define('CLIDISPLAY', false);
if (CLIDISPLAY) {
define('PRE', '');
define('PRE_END', '');
} else {
define('PRE', '<pre>');
define('PRE_END', '</pre>');
}
require_once("/etc/dbconnect.php");
$DBLink = new mysqli($VARDB_server, $VARDB_user, $VARDB_pass, $VARDB_database, $VARDB_port);
if ($DBLink->connect_errno) {
printf(PRE . "Connect failed: %s\n" . PRE_END, $DBLink->connect_error);
exit();
}
Be sure you have a normal php file at /etc/dbconnect.php with your credentials in it (do not put these in a web folder in case php fails one day and exposes your passwords! LOL). Note that this file can then be shared and loaded only once. It should invoke
# Sample execution
$Query = "select * from vicidial_users where user='6666' and active='Y' limit 1";
$Records = GetData($DBLink, $Query);
print_r($Records[0]); // Single record return access via [0] to access a field named "id": $Records[0]['id']
// Multiple record return access via array walking
foreach ($Records as $Record) {
print_r($Record);
}
$Query = "update vicidial_users set active='Y' where user='6666' limit 1";
UpdateData($DBLink, $Query);
Functions (can be loaded from the credentials file or within your working file or put in a "functions.php" file and "require_once('functions.php');".
function GetData($DBLink, $Query) {
if (DEBUG) {
echo PRE . "Query: $Query\n" . PRE_END;
}
if ($Result = $DBLink->query($Query)) {
if (DEBUG) {
printf(PRE . "Affected rows (Non-Select): %d\n" . PRE_END, $DBLink->affected_rows);
}
while ($Record = $Result->fetch_assoc()) {
$ReturnData[] = $Record;
}
return $ReturnData;
} else {
if (DEBUG) {
printf(PRE . "Errormessage: %s\n", $DBLink->error);
printf("Affected rows (Non-Select): %d\n", $DBLink->affected_rows);
echo "No Records Returned\n" . PRE_END;
}
return false;
}
}
function UpdateData($DBLink, $Query) {
if (DEBUG) {
echo PRE . "Query: $Query\n" . PRE_END;
}
if ($Result = $DBLink->query($Query)) {
if (DEBUG) {
printf(PRE . "%s\n", $DBLink->info);
printf("Affected rows (Non-Select): %d\n" . PRE_END, $DBLink->affected_rows);
}
return;
} else {
if (DEBUG) {
printf(PRE . "Errormessage: %s\n", $DBLink->error);
printf("Affected rows (Non-Select): %d\n", $DBLink->affected_rows);
echo "No Records Returned\n" . PRE_END;
}
return;
}
}

PHP newbie with a perplexing piece of code

this ought to be simple, but it doesn't seem to be working for me. i have tested it with good and bad passwords. no matter what, it will not go into the else statement. i am not sure what i am missing
my code:
$mysqli = mysqli_connect("localhost", "joeuser", "somepass", "testDB");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
} else {
$sql = "SELECT * FROM login_info";
$res = mysqli_query($mysqli, $sql);
if ($res) {
while ($newArray = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
$id = $newArray['first_name'];
$testField = $newArray['last_name'];
echo "The ID is ".$id." and the text is ".$testField."<br/>";
}
} else {
printf("Could not retrieve records: %s\n", mysqli_error($mysqli));
}
mysqli_free_result($res);
mysqli_close($mysqli);
}
If i send it a user and password that do exist it does the if statement fine, but if i send it a test for one that is not in the db it still won't do the else? why?
For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a MySQLi_Result object.
A query is only not successful if some serious error occurred. Simply because a SELECT query didn't match any rows doesn't make the query unsuccessful. You'll still get a MySQLi_Result object back. You'll want to check with mysqli_num_rows whether the result set contains any rows.
BTW, save yourself some nesting:
if (!$something) {
exit;
}
// continue as usual
No need for an else here, since you're exiting anyway. Makes things simpler.
Like this:
if ($res) {
while ($newArray = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
$id = $newArray['first_name'];
$testField = $newArray['last_name'];
echo "The ID is ".$id." and the text is ".$testField."<br/>";
}
}
if (!isset($id)) {
printf("Could not retrieve records: %s\n", mysqli_error($mysqli));
}

Categories