How to update entry in sql? - php

I cant figure it out. I have this variable (for example):
$level_building = "test,";
and this sql string:
mysql_query("UPDATE info_buildings SET building='$level_building' + building WHERE nick='$nick'") or die(mysql_error());
all i want to do is to add new text test, after existing text, but after updating it, sql shows 0 (building=0).. My sql output should look like this test,test,test,... Example: building=test,test,test, and each time i use sql string UPDATE it should write new test text in the same building string.. Sorry for bad english i hope you understand this.

In MySQL, + is for arithmetic addition. To concatenate strings, use CONCAT():
UPDATE info_buildings
SET building = CONCAT('$level_building', building)
WHERE nick = '$nick'
All the MySQL string functions can be found here.
However, I recommend you reconsider your table design. Putting comma-separated lists in a single column is usually poor design. You should use a separate table with a row for each value.

Related

A column with implanted PHP functionality

Lets say I have this PHP function:
function strlow($string){
strtolower(trim($string));
}
Now lets say I have a table with 2 columns [id - title] and I want to make all titles that are going to be inserted into the table in lowercase, The usual way is
$title = strlow($title);
$query = "INSERT INTO table (title) VALUES ($title);
Is there for example a way to implant in the column itself in the database the function, So instead of doing the strlow() by the PHP, the Database does it?
If yes, I wish for an example built on mine.
You could update your query to handle this if you really wanted (but I would still rather do this in the application layer) using the MySQL TRIM and LOWER commands:
INSERT INTO table (title) VALUES (TRIM(LOWER(($title)))
The reason I say I would rather do this in the application layer is that if you decide to switch database systems in future, you need to remember to port over all your database formatting rules such as these at that time too which although doesn't seem too bad now, trust me, in the future, you will forget.
In addition to this, if you ever want to add further logic to what you are putting in to the database you will likely find your options more limited in MySQL than you will in your application layer.
Also, please for my sanity look up how to use parametrized queries because you are wide open to SQL injection attacks at the moment. There is a great post here that covers this.
$query = "INSERT INTO table (title) VALUES (LCASE($title));

sql update statement where 2 condition apllies

This is quite a basic question, but have not found that much on-line to support.
I need to use a simple update statement in mysql (I know i should use mysqli but not yet ready for this update)
Given That I am working with a database made of a fixed number of items I want that the update apllies only when 2 conditions together are true.
my idea is something like
$sql ="update `members` set `description`='$description[$index]' WHERE id='1' AND fruit = 'banana'";
Is this the proper way of selecting the record to be updated?
Many thanks
Manu
That's how you'd do it more or less, here's a refined one:
$sql ="update `members` set `description`=? WHERE `id`='1' AND `fruit` = 'banana'";
1) See how I put the ? instead of the array? There are smart objects in PHP (read about "Prepared Statements") which allow you to put a parameter "spot" in the query and later have a value instead of it. This makes your query much more secure.
2) I added '`' around your columns. It's not mandatory, but it makes sure that your columns aren't mistaken for something else.
Yes that should work but it's safer to wrap array values in a string in brackets:
$sql ="UPDATE `members` SET `description`='{$description[$index]}' WHERE id='1' AND fruit = 'banana'";
Also make sure $description is somehow filtered or validated, before plugging it directly into the string.
NOTE: Best practice dictates that you use all caps for all SQL keywords, allowing easier differentiation between keywords and your values. Yours has half and half update and set lowercase; WHERE and AND caps, which is worse than going with all lowercase.
[edit] I agree with Daniel Saad that you should be using prepared statements here as well.

Getting a Mysql Results without knowing a column name [duplicate]

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...

SELECT FROM a database named from a value in a JOIN

I have a SQL statement that has to pull information from two databases, one is a constant and known database, and the other is dynamically found in the first database. The databases structure looks like this:
(database) lookup
(table) test
(fields) key, database_name
(row sample) "foo", "database_foo"
(database) database_foo
(table) bar
(fields) important1, important2
(row sample) "silly", "test"
So my SQL statement looks like this:
SELECT
test.key as key,
test.database_name as database_name,
bar.important1 as important1,
bar.importnat2 as important2,
FROM
lookup.test as test,
(database_name).bar as bar, # this, obviously, doesn't work
WHERE
key = 'foo'
LIMIT 1;
Is there a way I can make this work, or is it better for me to just do two separate SQL statements, one for the lookup, and one for the database?
If you must do it this way then you need to use dynamic sql and a two statements.
You have your query built as a string and then you run an EXEC on the query once it's constructed.
In this case you would have a string variable for the db name, then you would create a query from this variable and your literal query, then you would simply execute it.
Be aware, though, this makes you vulnerable to SQL Injection if you don't control the input parameters.
Erland Sommarskog has a great primer on using dynamic SQL:
http://www.sommarskog.se/dynamic_sql.html
EDIT: From #BryanMoyle comment below, you will likely need to do both a separate query and dynamic sql. You need to extract the value in order to determine the other DB name... Since you cannot use the DB name as a variable otherwise, you'll need to SELECT this information first, then stick it into the subsequent query.
I personally go for 2 separate statements; it would make it easier to control for errors such as the the lookup provides a row, that the row provides a valid database, etc.
As Matthew pointed out, beware of SQLIA and sanitize all user input. I like to MD5 hash inputs and compare to the hash of the value looked up.
I'd go for two separate queries, mediated by php: It's simpler, more robust, and will keep you sane and productive. Write one query to find out which database you should be talking to. Use php (not SQL) to direct your query to that database:
$row = $lookup->prepare("SELECT database_name WHERE key = 'foo'")->execute()->fetch();
$db = $row[0];
Then you contact $db and ask for the row with key foo. Use PHP code to select the right open connection, or switch databases inside the connection with USE:
$query2 = "USE " . $db . "; SELECT * FROM bar where key == 'foo'"

MySQL - Simple search for ID and return name

G'day,
I'm not familiar with MySQL and this will probably be an easy question!
I am trying to mod a Joomla plugin and am working with this code that works well for a similar function:
$q="SELECT `".$naming."` AS naming FROM `#__users` WHERE `id`='".$jomsocial_event->creator."' ";
$db->setQuery($q);
$eventcreatorname = $db->loadResult();
$eventcreator = ''.addslashes($eventcreatorname).'';
What I need to do is lookup the field id in the table community_groups and return the matching field name. What I have is (note that $jomsocial_event->contentid contains the group ID):
$q="SELECT `".$naming."` AS naming FROM `#__community_groups` WHERE `id`='".$jomsocial_event->contentid."' ";
$db->setQuery($q);
$eventgroupname = $db->loadResult();
$eventgroup = ''.addslashes($eventcreatorname).'';
It returns nothing as the query is wrong; what should it be for my usage?
I'd work backwards from the database.
i.e. turn on SQL logging and look at what's actually arriving in the database. Tweak as necessary by playing with the resulting SQL until you get what you want (and expect) and then implement that in your code.
Take a look at your generated query in the debugging from Joomla.
Run it against mysql directly and see where it goes wrong.
Also, I'd use the JDatabaseQuery API because you are much less likely to get errors with quoting etc. It looks to me like you are treating id as a string not an integer.

Categories