I am trying to check if a table has a certain column in it, and if not add that column to it. My code appears to work fine as long as the input value does not have an # sign. I have tried surrounding
'$email'
with and without single quotes as an input string. Any help would be really appreciated.
$email = strtolower(mysql_real_escape_string($_SESSION['email']));
$result = mysql_query("SHOW COLUMNS FROM `selections` LIKE '$email'",$conn);
$exists = (mysql_num_rows($result))?TRUE:FALSE;
if ($exists == FALSE) {
$query2 = "ALTER TABLE selections ADD $email VARCHAR( 120 ) NOT NULL";
$add= mysql_query($query2,$conn);
var_dump($query2);
echo("this error". mysql_error());
}
$query2 was taken directly from phpmyadmin and seems to work there even with an # sign input
Thanks for your help!
Before anything else, please, please consider doing this in another way. You will be adding a field to a table for every email - what you probably do not know is that this increases the size of your table by increasing the size of the rows, and also limits you to a fixed number of fields (This link clearly highlights a total of 65535 bytes per row max. Every VARCHAR character, depending on charset, is between 3 and 8 bytes)
The real reason why your request is failing is because # is a special character in your SQL queries and phpmyadmin happens to be smart enough to escape it. # denotes a variable in the SQL dialect uses by MySQL. You can either backtick-escape it for MySQL, or you can quit using this in favour of a table structure like this:
selection:
* id
* your metadata here
emails:
* id
* email_address
selection_emails:
* id
* selection_id
* email_id
The third table is called an associative table. It allows you to keep normalizing your data.
You can surround the email with curly brackets {$email} to define it explicitly as a variable within a string, but you probably also need to escape odd characters in this variable before this.
When altering the table you should also surround this with back-ticks, to allow for odd characters.
The best approach would be to use parameterized queries, and drop the DEPRECATED mysql library. And also to not allow odd characters to be used in field names.
I would also question why you are adding email as a new column.
Related
I have a php script which selects from a MySQL table. The Table Content is set to UTF8, so is the php script interfacing with it.
The input strings are real_escaped. I am facing the following issue:
Given the following data in the table:
ID Username
1 Test
2 Test1
3 Test-A
The following SQL returns the IDs for 1 and 2 successfully but when asked for the 3rd it returns nothing.
SELECT `ID` FROM `User` WHERE `Username` = '$User'
Why is it not returning when I ask for the ID where Username = Test-A?
Is it because the Username contains a minus?
It has to be a different string. Double check the dash/hyphen mark in both cases (may be different unicode characters like described here) - it happens frequently when copying and pasting data from "rich" text editors.
Also check for whitespaces.
Depending on what you mean by "real_escaped" it might be the case that your username is escaped turning into something similar to ('Test\-A') which essentially does not exist.
Print out the value of the $User to check what you're sending to MySQL.
On top of that, you are using old outdated practices, there are better ways of querying the database securely with PDO::prepare (http://us1.php.net/manual/en/pdo.prepare.php), use those examples there.
This question already has answers here:
Get table column names in MySQL?
(19 answers)
Closed 9 years ago.
As I am still learning PHP and MySQL, I would like to know if it is possible to query a table without knowing it's name. Knowing the table I am querying and the column I would like to retrieve, I can write something like
$book_title=$row['book_title'];
Then I can use the resulting variable later in the script. In each case, each book category table will have a column of interest with a different name. I have several tables on which I am running queries. I am able to query any table by using a variable that always evaluates to the correct table name, because all the input from users corresponds to the tables in the database, so the $_POST super global will always carry a correct table name. The problem is for me to have a
$variable=$row['column'];
in cases where I do not know a column name before hand even though I know the table name.
My queries are simple, and look like
query="select * FROM $book_categories WHERE id=$id";
$row = mysqli_fetch_array ($result);
$variable=$row['?'];
The question mark say, I do not know what column to expect, as it's name could be anything from the tables in the database!
Since I have several tables, the query will zero on a table, but the column names in each table varies so I would like to be able to use one query that can give me an entry from such a column.
I hope my question is clear and that I am not asking for the impossible. If it's ambiguous, I care to elucidate (hope so).
I'm not sure what you mean, but it is possible to reference specifc columns by typing index (starting with 0) something like this: $row[0], $row[1] where 0 indicates the first column, and 1 indicates the second column from the returned recordset.
Example:
If you have a select-statement like this:
SELECT title, author FROM books
You could reference these two columns with $row[0], $row[1]
If you try to get the value of $row[2] you will get an unassigned value because there are only two columns (0 and 1) from the recordset.
If you have a select-statement like this:
SELECT * FROM book_categories
and the recordset returns three columns, then you could access these with $row[0], $row[1] and $row[2]. $row[3] does not exist because there are only three columns (0,1 and 2)
Since you are learning maybe we could take some time to explain why this is possible but many people (including myself) would say this is bad -- or at least dangerous
Why you can
Your SQL query is basically a text string you send to the DB server, which decode that string trying to interpret it as SQL in order to execute the query.
Since all you send to the DB server is text string, you could build that string however you want. Such as using string interpolation as you did:
select * FROM $book_categories WHERE id=$id
That way, you could replace any part of your query by the content of a variable. You could even go further:
$query FROM $book_categories WHERE id=$id
Where $query could by SELECT * or DELETE.
And, why not initializing all those variables from a form:
$book_categories = $_POST['book_categories'];
$id = $_POST['id'];
$query = $_POST['query'];
Great, no? Well, no...
Why you shouldn't
The problem here is "could you trust those variables to only contain acceptable values?". That is, what would append if $book_categories somehow resolve to one table you didn't want to (say myTableContainigSecretData)? And what if $id resolve to some specially crafted value like 1; DELETE * FROM myImportantTable;?
In these conditions, your query:
select * FROM $book_categories WHERE id=$id
Will become as received by the DB server:
select * FROM myTableContainigSecretData WHERE id=1; DELETE * FROM myImportantTable;
Probably not what you want.
What I've tried to demonstrate here is called SQL injection. This is a very common bug in web application.
How to prevent that?
The best way to prevent SQL injection is to use prepared statement to replace some placeholders in your query by values properly shielded against SQL injection. There was an example posted a few minutes ago as a response to an other question: https://stackoverflow.com/a/18035404/2363712
The "problem" regarding your initial question is that will replace values not table or columns identifiers.
If you really want to replace table/columns identifiers (or other non-value part of your query) by variables contents, you will have to check yourself the content of each of these variables in order to prevent SQL injection. This is quite feasible. But that's some work...
I try to query a mysql column which has the name "5". This outputs the wrong column which has the name "22".
This is my php code, $pid is the variable I am getting from the android app and is always a number. When I search with $pid = 5, instead of getting the column "5" with artist1, it is getting the column "22" with eternal1.
Basically it confuses the Column Name with # in the first print screen. If the # doesn't exist, then it searches correctly; so if I search with 16 I get the column 16. How do I fix this?
$pid = $_GET["pid"];
$result=mysql_query("SELECT * FROM TableComments WHERE `$pid` IS NOT NULL ");
http://imgur.com/WFsfEtB
http://imgur.com/rZA27XC
This is by design in the SQL dialects I can think of offhand. I know several people who, out of habit, add order by 0 desc or order by 1 to ad hoc queries, the first to pick what typically is the ID column and the second what is often a "Name" column or similar. They're querying based on the ordinal position of the field in the query (or the schema, in the case of *)
In order to get a column named 5, you need to use the appropriate SQL quoting mechanism for your dialect and configuration. As an example, Microsoft Sql and Access would typically use select * from tablecomments where [5]=5; in Postgres and Oracle you'd use select * from tablecomments where "5"=5, and in Mysql, Quoted Identifiers are quoted with a backtick select * from tablecomments where `5`=5. In Microsoft SQL you can also make things more like Oracle and Postgres if your session has SET QUOTED_IDENTIFIER ON, in which case you'd use quotes instead of square brackets.
As an aside, but a very important one, you should not take user input and directly embed it in SQL. If someone were to intercept the HTTP transmission between your Android app and your PHP app (trivial with a proxy like Charles or Fiddler), they'd be able to replay the http request with arbitrary SQL injected. As other commenters have noted, please use a parameterized query instead.
Since you're trying to modify the query itself rather than the parameters, you may need to consider whitelisting the allowed field names (or compare the string you're sent against the fields represented in the schema).
Wrap the column-name into backticks:
SELECT * FROM TableComments WHERE `$pid` IS NOT NULL
Start using PDO instead of old, unsafe and deprecated mysql_*
I've just noticed that if I do a MySQL request like this one:
SELECT 1 FROM myTable WHERE id = 'asdf'
Then the string 'asdf' is casted to 0.
It means that I have a record with id 0 this will match.
The format of the id field is int(8).
What is the best way to proceed:
I need to check (by PHP for example) that my value is numerical only?
There is a MySQL way to do that?
I must remove my record with id 0? (bad)
Just write your queries so that they don't use numeric fields as if they were textual ones.
If id is a numeric field, then your where clause can never be useful. Yes, it would be good if MySQL actively complained about it - but fundamentally you shouldn't be writing code which runs bad queries to start with.
How did that query enter your system? Is the 'asdf' part direct user input? Can you use parameterized SQL instead?
If you're genuinely intending to query a numeric field, you should make sure that your input is numeric first. Convert the text to an integer in your calling code, not in the database.
You must first sanitize your inputs via PHP.
$id = 'asdf';
if(is_numeric($id)){
$query("SELECT 1 FROM myTable WHERE id = $id");
}else{
die("ID is not numeric");
}
Or you can do:
SELECT 1 FROM myTable WHERE id = 'asdf' AND 'asdf' REGEXP '^-?[0-9]+$'
This would cause the regex to = false, causing no rows to return.
Since pdo prepared statements binding with correct types will not raise any error (except if mysql strict mode is enabled), your only choice is to ensure and control the types of your variables within your php to "correct" the permissivity of these languages.
[thanks to commentators]
This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 8 years ago.
So I have a primary key column called key. I'm trying to select the row with key = 1 via this code:
$query ="SELECT * FROM Bowlers WHERE key = '1'";
$result = mysql_query($query) or die(mysql_error());
For some reason, I'm getting this result:
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 'key = '1'' at line 1
The mysql statement works for using other keys, ie WHERE name = 'djs22'.
Any ideas?
key is a reserved word, try putting ticks around it:
$query ="SELECT * FROM `Bowlers` WHERE `key` = '1'";
$result = mysql_query($query) or die(mysql_error());
To see all the reserved words, go here and scroll down:
http://dev.mysql.com/doc/refman/5.1/en/reserved-words.html
'key' is a reserved keyword, put backtick quotes around it:
"SELECT * FROM Bowlers WHERE `key` = '1'"
Without checking, it's likely that "key" is a reserved word in MySQL.
Try wrapping it in backticks
$query ="SELECT * FROM Bowlers WHERE `key` = '1'";
You should write the column name key in quotes
$query ="SELECT * FROM Bowlers WHERE `key` = '1'";
Otherwise it is a keyword
I run into that all the time. MySQL has a crap load of reserved words. And when you come across one, the mysql error function is not even nice enough to let you know what is wrong.
The only thing you can do is change the column name. I accidentally used "date, to and from" the other day. Was pulling my hair out when it dawned on me, DuHH!!! those are DB reserved.
You can wrap all kind of quotes around it, it does not matter when it references a column name. Reserved is reserved!
It is common practice to to do a couple of things.
1) When making tables: Split resource type with resource name using underscore. Example: xref_userMessages
This would mean it is a cross reference table for User messages.
2) Other examples of table names: msg_Messages | sys_Settings | cli_Logins
So any other table made related to messages would be called msg_??? , not only does this keep them grouped together in phpMyadmin but makes remembering the names easier too.
3) When Making columns: Never use a reserved. Thus causing key columns to always be 6 didgets. Example: admkey | usrkey | msgkey | clikey grpkey
Obviously Admin Key | User Key | Message Key | Client Key | Group Key
So this means "msg_Messages" keys are "msgkey" and the xref table would be xref_Messages and its keys are xref_msgkey. Following this logic you not only know what to name everything without even thinking about it, but you never run into any reserved words doing it.
4) Examples of Column names: dateInsert dateStart timeCreate admName admAddress admPhone admCell
Just like above there is a logic to it. Placing purpose/owner and noun/item together makes the name and again avoids reserved words.
Last Example:
Table: users_Admins users_Clients
Key: admkey usrkey
Table: msg_Messages
Columns: msgkey admkey usrkey msgRead msgMessage msgTitle
Just in this short example I avoided 2 reserved words. Key and Read
So in short, your problem is not reading a primary key. It is a problem with column names.
MySQL is seeing your code as having a syntax that has commands out of place. SELECT read ... or SELECT key ... it doesnt matter if you put quotes around it or not. MySQL is basically seeing ...
SELECT (SELECT,WHERE,FROM) FROM select,from,where
WHERE SELECT = WHERE & FROM = SELECT. hehehehehehehe
Putting a different kind of quote around this will not change the confusion level you just sent to MySQL.
Mixing my mistake and your mistake together looks like this...
SELECT key,from,to,date FROM my_table WHERE key='1';
// Same as...
SELECT SELECT,SELECT,SELECT,SELECT FROM my_table WHERE SELECT='1';
The first one you can't really tell by looking at it there is anything wrong with it. The second one it is obvious that it is not right and won't work. However, according to MySQL they are the SAME THING.
MySQL receives this syntax as so... SELECT? You told me to SELECT 5 times, never told me what to even select. You get the FROM right, but then you ended with a left hook telling to select something else, not only did you not tell me what to select again but you threw in an NULL='1'; what the heck is that all about?
This is why when you make these kinds of errors the error function doesn't even report what the heck happened. There were so many errors it can't throw you an error number so it just stops.
So this means your syntax is like this
SELECT * FROM Bowlers WHERE SELECT = '1';
Sometimes I get frustrated and say, "I wish MySQL was smarter than this!!!" But then I realize i would have to trade the key words in for a lesser valued database. Each one of those reserved words represents a word that is doing a whole lot more work on the database side for me. When I first started to learn programming I had to write my own text input field sub routines, so I appreciate all the neat things MySQL does for me.