Selecting fields using variables for the fields - mysql

I have created a dropdown list where the user can select the fields they wish to have displayed. I can create a variable, say $field_list which then has 3 (user selected) fields, say title, first_name,last_name. So my SELECT statement would read (as a php statement)
$sql=" SELECT $field_list from my_table ";
which operates as
"SELECT title, first_name,last_name from my_table ";
The problem then arises when trying to display the data from each of these fields. I am trying to use the stucture as follows
$result=mysql_query("$sql");
while ($myrow = mysql_fetch_array($result))
{
echo "the data is $myrow["x"];
}
Howvere, I want to be able to use different values for x which are extracted from the $field_list using substr(). Normaly I would do this by using $x and changing the values as appropriate, but this syntax does not work. Any help would be appreciated.

Careful with quoting. Try echo "the data is " . $myrow[$x]; or echo "the data is {$myrow[$x]}";

Related

Searching for multiple values in 1 query

If I have a database having 2 fields, Roll no and name and I have a list (of n values) of roll numbers for which I have to search the corresponding names.
Can this be done using just one query in SQL or HQL?
SELECT name FROM [table] WHERE id IN ([list of ids])
where [list of ids] is for example 2,3,5,7.
Use the IN operator and separate your Roll no's by a comma.
SELECT name
FROM yourtable
WHERE [Roll no] IN (1, 2, 3, 4, etc)
You can use the IN statement as shown above.
There are a couple of minor issues with this. It can perform poorly if the number of values in the clause gets too large.
The second issue is that in many development environments you land up needing to dynamically create the query with a variable number of items (or a variable number of placeholders if using parameterised queries). While not difficult if does make your code look messy and mean you haven't got a nice neat piece of SQL that you can copy out and use to test.
But examples (using php).
Here the IN is just dynamically created with the SQL. Assuming the roll numbers can only be integers it is applying intval() to each member of the array to avoid any non integer values being used in the SQL.
<?php
$list_of_roll_no = array(1,2,3,4,5,6,7,8,9);
$sql = "SELECT FROM some_table WHERE `Roll no` IN (".implode(", ", array_map ('intval', $list_of_roll_no)).")";
?>
Using mysqli bound parameters is a bit messy. This is because the bind parameter statement expects a variable number of parameters. The 2nd parameter onwards are the values to be bound, and it expects them to be passed by reference. So the foreach here is used to generate an array of references:-
<?php
$list_of_roll_no = array(1,2,3,4,5,6,7,8,9);
if ($stmt = $mysqli->prepare("SELECT FROM some_table WHERE `Roll no` IN (".implode(",", array_fill(0, count($list_of_roll_no), '?')).")"))
{
$bind_arguments = [];
$bind_arguments[] = str_repeat("i", count($list_of_roll_no));
foreach ($list_of_roll_no as $list_of_roll_no_key => $list_of_roll_no_value)
{
$bind_arguments[] = & $list_of_roll_no[$list_of_roll_no_key]; # bind to array ref, not to the temporary $recordvalue
}
call_user_func_array(array($statement, 'bind_param'), $bind_arguments);
$statement->execute();
}
?>
Another solution is to push all the values into another table. Can be a temp table. Then you use an INNER JOIN between your table and your temp table to find the matching values. Depending on what you already have in place then this is quite easy to do (eg, I have a php class to insert multiple records easily - I just keep passing them across and the class batches them up and inserts them occasionally to avoid repeatedly hitting the database).

Unexpected field in Mysql fetch data

I have a query in which the data is lifted from the database.
Eg: I have Category as a field which has values like Doctors, Pathologists etc which is taken from the database.
Category
--------
Doctors
Pathologists
Pediatrics/Child Specialist --->> Unwanted data
The problem is there is a data(value) in 'Category' field which is unexpectedly showing in the list which is not in my database. I even tried to drop the table entirely and reload it but that field is still showing.
Can anyone tell me why is this happening?
Additional Info
function getTierCategory()
{
echo "</br>";
$result = mysql_query("SELECT DISTINCT Category FROM doctors order by Category asc")
or die(mysql_error());
while($tier = mysql_fetch_array( $result ))
{
echo '<option value="'.$tier['Category'].'">'.$tier['Category'].'</option>';
}
}
I have tried renaming the field but how can I if this value is not even in my database.
My Database looks like
Category | Qualification | State | District
--------------------------------------------
and so on
Log in to your database in PHPmyadmin or something like that and check results of your mysql query.
In some complex queries you can receive redundant fields (on example indexes when you have counting variable in PHP) or NULL values.
mysql_fetch_array() returns results in two ways:
number indexed array ($array[0] etc)
associative array ($array['field_name'] etc)
Try with mysql_fetch_assoc or mysql_fetch_row instead. Also PDO_MYSQL API is recommended to use for MySQL querying. It has more convenient form.

MySQL Select* returns everything but the id column

I have a database with 2 tables I wish to pull data from both and display it in an html table. When I execute the below select statement I seem to get everything but the auto_increment column "id"
>mysql connection strings here.
$query = "SELECT Hotels.*,surfcup_Rates.*
FROM Hotels
LEFT JOIN surfcup_Rates
ON Hotels.id=surfcup_Rates.hotelID";
Then I use load the query into $result.
Later I load it into mysql_fetch_array and loop it into an html table.
while ($row = mysql_fetch_array($result)) {
echo "</td><td>";
echo 'Delete';
echo "</td><td>";
echo $row['id'];
echo "</td><td>";
echo $row['preferred'];
>and so on...........
Everything works: the join, the select statement and data loads into the table
perfectly. All except the id column from the first table. I wish to use the id to allow the user to delete a record. The user will be adding data to the tables from a password protected "back-end" for data entry.
Is there something wrong with my select statement? Or am I missing something. Any help will be greatly appreciated.
Thank You,
Dave.
Assuming that your surfcup_Rates table has an id column (you don't say that explicitly, but it seems likely), then you either need to "rename" one of the id columns from the two tables so they don't collide when mysql_fetch_array figures out what to return for each row, or I believe you can just swap the two parts of the SELECT output selectors, given that you don't seem to care about the id from the surfcup_Rates table:
$query = "SELECT surfcup_Rates.*,Hotels.*
FROM Hotels
LEFT JOIN surfcup_Rates
ON Hotels.id=surfcup_Rates.hotelID";
In this case, the id from Hotels will mask the one from surfcup_Rates, not the other way around as you have it.
Try
$query = "SELECT *
FROM Hotels
LEFT JOIN surfcup_Rates
ON Hotels.id=surfcup_Rates.hotelID";
NOTE: I would probably do all the fields in the select
SELECT Hotels.id as HotelId, surfcup_Rates.id as SurfCupId,....
[others here] ... FROM Hotels
LEFT JOIN surfcup_Rates
ON Hotels.id=surfcup_Rates.hotelID
Does the surfcup_Rates table also have a field called id? If so, mySQL won't know whatid to use, hotel or surfcup_Rates.
In this case you have a couple of options,
changing the table structure, but do so at your own risk as other things could break
use an alias (best method)
DISCLAIMER
I have never used the following method in PHP myself, I have seen it in SAP and Zimbra, as this isn't a discussion forum on these aspects, instead of a debate I thought I would put a disclaimer that it may not work but as mentioned above and in my comment below I have seen it work
call hotels.id
I hope this helps

MySQL: The easiest way to display all data from the table by getting TABLE_NAME olny (no column information) on the html page

MySQL db named "db2011" has several tables.
Using php variable $tablename (the tablename is correct, the table exists in the db), how to display the data from "db2011".$tablename on the html page?
Can it be done by performing just 1 query - to select all data by $tablename?
I think it can be done in 2 steps, but I'm asking any better solution (in case if this one is not good):
Step1: Get column names by performing
"SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='db2011' AND TABLE_NAME='".$tablename."'";
Step2: Build and perform a query with SELECT + list of columns separated by comma FROM $tablename?
P.S. I know the data could be huge to be displayed on the html page. I will limit it by 100 rows.
Any better ways?
Thank you.
I am assuming you are doing this in PHP. It may not be elegant, but it gets it in one query. I think you want to display the table columns as well as the data in one query.
<?php
$sql = "SELECT * FROM $tablename";
$res = mysql_query($sql);
$firstpass = TRUE;
while($row = mysql_fetch_assoc($res)){
if($firstpass){
foreach($row as $key => $value) {
//store all the column names here ($key)
$firstpass = FALSE;
}
}
//Collect all the column information down here.
}
?>
Why not just SELECT * FROM $tablename limit 100;?
You would get all the column names back in the result set. Unless you also need the column type on your webpage I would go with just that

Using enum in drupal

I have a mysql table id,name,gender,age religion( enum('HIN','CHR','MUS') ,category(enum('IND','AMR','SPA') where last 2 are enum datatype and my code in drupal was
$sql="SELECT * FROM {emp} WHERE age=".$age." and religion=".$rel." and category=".$categ;
$result=db_query_range($sql,0,10);
while($data=db_fetch_object($result))
{
print $data->id." ".$data->name."<br>";
}
I get no result or error . I'm trying different query with each field and all are fine except using enum.
for ex: $sql='SELECT * FROM {emp} WHERE religion="'.$rel.'"';
Is there any problem in using enum datatype in drupal
Enum is not something that I believe drupal can make with the schema API, which is what you in most cases want to use for modules and stuff. Also you are lacking an ending ) in your reference to it, but I'm sure you did it right when your made the table.
Enum is only a constraint that is built into the database when inserting values. So if you try to insert an invalid value, you will insert an empty string instead. So it wont have any effect on Drupal querying to get data. It also wont have any effect when Drupal insert values, other than converting invalid values to empty strings. You might want to check the your data, to see if it is as expected. You might just get no results because your query doesn't match anything.
Another thing is the way you construct your queries is a big NO NO, as it's very insecure. What you should do is this:
db_query("SELECT ... '%s' ...", $var);
Drupal will replace %s with your var and make sure there is no SQL injection and other nasty things. %s indicates the var is a string, use %d for ints and there are a few others I can't remember just now. You can have several placeholders like this, and they will be insert in order, much like the t function.
Seconding Googletorps advise on using parameterized queries (+1). That would not only be more secure, but also make it easier to spot the errors ;)
Your original query misses some quotes around your (String) comparison values. The following should work (Note the added single quotes):
$sql = "SELECT * FROM {emp} WHERE age='" . $age . "' and religion='" . $rel . "' and category='" . $categ . "'";
The right way to do it would be something like this:
$sql = "SELECT * FROM {emp} WHERE age='%s' and religion='%s' and category='%s'";
$args = array($age, $rel, $categ);
$result = db_query_range($sql, $args ,0 , 10);
// ...