MySQL database manipulation with PHP - php

Spent the last few days researching this, but I think I'm just not getting it... I can usually do what I need to with PHP but am new to MySQL
I set up a MySQL database to hold some photos. The photo's are in separate galleries (gallery is denoted by a gallery field). The photo's are also indexed by an id number.
When displaying the photos (it all works perfectly up to now...), I would like to be able to jump to the next or previous photo in the gallery, but can't just us the next or previous id, as it could be from a different group (found that out the hard way ;)
from my research, I feel like I need to use this:
$sql = "SELECT id FROM gphoto WHERE gallery='$g' ORDER BY id DESC";
$query = mysqli_query($db_conx, $sql);
But $query doesn't seem to give me what I expect. It feels like $query it should contain an array if all id's which contain gphoto, and I should be able to just find my current id number, then jump one up or down, but when I try to read $query I get:
Cannot use object of type mysqli_result as array
I'm obviously misunderstanding something
Some people have suggested:
$result = mysqli_fetch_assoc($query);
I had tried this after reading the online manual extensively, but for some reason it only lists one item... in this case the last record.
If I run it as ASC, it lists the first. Should it be listing all records like I expect, or is it a different command?
C)

+1 for Fabio's response.
A good advice is to use PDO interface for accessing databases in PHP. It's a meaningful interface to construct, execute and fetch the results of your queries without the knowledge of the used db driver.
http://php.net/manual/en/book.pdo.php

You need to fetch data from database after executing your query to handle mysqli object you have just created
$query = mysqli_query($db_conx, $sql);
$result = mysqli_fetch_assoc($query);
Now you have the array you were looking for in your variable $result

if ($result = mysqli_query($db_conx, $query)) {
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
//mysqli_fetch_assoc fetches data by row
}
}
You are only getting 1 row, thats how mysqli_fetch_assoc works. If you want the entire result to be an array of the rows, use mysqli_fetch_all
I would recommend using PDO however like #ceadreak suggested.

Related

How to get the column names of a result returned by select query

I am building a reporting tool where an user can enter a SQL query and the tool will return the results in a CSV file. In addition to just writing to a CSV file, I also need to perform some additional logic here. So SELECT INTO OUTFILE will not work for me.
I know that executing arbitrary user provided SQL queries is bad, but this tool is going to be used only internally, so security shouldn't be a concern. Also I am limiting it to only select queries.
Now when I export the data in CSV format, I also want to output the column names of the query as the first row in the CSV file.
So my question is, is there a way to fetch the column names of a SQL query in PHP using PDO?
Mysql client tools like Sequel Pro are able to display the column names while displaying query results. So I am assuming that it should be possible, but I am not able to find it.
Here I am not writing full PDO connection code. You can use below code/logic to get the return column name.
$stmt = $conn->query("SELECT COUNT(*), first_column, second_column FROM table_name");
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$columns = array_keys($row);
print_r($columns); // array(0 => COUNT(*), 1 => first_column, 2 => second_column)
The keys of the row result are the column names. You can display them like so:
$conn = mysqli_connect(YOUR_CONNECTION_INFO);
$result = mysqli_query($conn, YOUR_QUERY);
$row = mysqli_fetch_assoc($result);
foreach ($row as $key=>$value) {
echo $key;
}
You said security wasn't an issue since the code would only be used internally, but what happens if you create a new database user with limited rights and connect to the database using that user.
That way you can set up the rights as you want from your database and won't have to worry about users dropping tables.

Debugging assistance request. PHP and MySQL query [duplicate]

I've made a form that allows users to submit their name, a comment and a score from 1-6, which then is saved in a table in their respective fields; name, comment and score. I wan't to display the average score.
This is what I've found out so far:
$result = mysql_query("SELECT AVG(fieldName) FROM tableName");
How do I echo this out?
Give your result an alias, It makes accessing it easier.
Use mysql_fetch_assoc() to get your results
$result = mysql_query("SELECT AVG(fieldName) AS avg FROM tableName");
$row = mysql_fetch_assoc($result);
echo $row['avg'];
FYI, mysql_* is obsolete. Try PDO or mysqli instead.

Storing the results of pg_query in a table

Is it possible to store the results of a query in a table?
For example, I currently run a query using the following approach in php:
$sql = "SELECT id FROM mytable";
$query = pg_query($connection, $sql);
I then use pg_fetch_row() to access the result and return it to the web-browser. However, I would like to also store the results in a new table. I understand that I could run the same query twice so I would also have:
$sql_2 = "CREATE newtable AS SELECT id FROM mytable";
$query = pg_query($connection, $sql_2);
I was curious if there was a more efficient way of structuring my queries, so that I could both access the results, and insert the results into a table through just one query.
Unfortunately the CREATE TABLE command doesn't appear to accept a RETURNING clause, so that doesn't allow just having that command also return the results. So you're likely to need to do two queries.
You could swap the queries to create the new table first, then fetch the results by selecting out of that new table. Accessing that newly created table may be a bit faster than doing the initial query twice since postgres won't need to look over any irrelevant data. This would also guarantee that the same results appear in both places.

Can I just SELECT one column in MYSQL instead of all, to make it faster?

I want to do something like this:
$query=mysql_query("SELECT userid FROM users WHERE username='$username'");
$the_user_id= .....
Because all I want is the user ID that corresponds to the username.
The usual way would be that:
$query=mysql_query("SELECT * FROM users WHERE username='$username'");
while ($row = mysql_fetch_assoc($query))
$the_user_id= $row['userid'];
But is there something more efficient that this?
Thanks a lot, regards
You've hit the nail right on the head: what you want to do is SELECT userid FROM users WHERE username='$username'. Try it - it'll work :)
SELECT * is almost always a bad idea; it's much better to specify the names of the columns you want MySQL to return. Of course, you'll stil need to use mysql_fetch_assoc or something similar to actually get the data into a PHP variable, but at least this saves MySQL the overhead of sending all these columns you won't be using anyway.
As an aside, you may want to use the newer mysqli library or PDO instead. These are also much more efficient than the old mysql library, which is being deprecated.
Not only can you, but you should. Unfortunately too many young developers get in the habit of selecting far too much data. Once you run your query, you don't need to do a while loop since you only have one record coming back. Instead, just use the following:
$sql = sprintf( "SELECT userid FROM users WHERE username = '%s'", $username );
$result = mysql_query( $sql ) or die( mysql_error() );
$data = mysql_result( $result, 0 );
if ( $data ) echo $data; // first userid returned
The second parameter of mysql_result() is the row index you would like to retrieve. 0 is first.
The "usual" way is to only select the columns that you need.
Any column that is part of the select and is not needed will slow down the retrieval. Partly because of network traffic and partly because the database engine can apply certain optimizations if only some columns are selected.
And select * is usually frowned upon in production code.
Your query is correct:
$query = mysql_query("SELECT userid FROM users WHERE username='$username'");
This will work if done correctly. Note that $username must be correctly escaped with mysql_real_escape_string. I'd recommend looking at parameterized queries to reduce the risk of introducing an SQL injection invulnerability.
One other thing you can change is to use mysql_result instead of your loop:
$the_user_id = mysql_result($result, 0);
This assumes that know you'll get only one row.
Yes, that's a great optimization practice!
Also, if you want to go a step further and make it super-optimized, try adding a LIMIT, like this: $query=mysql_query("SELECT userid FROM users WHERE username='$username' LIMIT 1");
This, of course, assumes you expect only one userid to be returned and will make the database engine stop once it finds it.
But, the most important thing: ALWAYS ESCAPE/SANITIZE YOUR INPUT DATA! (can't stress this well enough)
You can do this with a single line of code
echo array_values(mysqli_fetch_array($mysqli->query("SELECT name FROM user WHERE id='$userid'")))[0];
You must connect to the database as shown below before using this
$mysqli = new mysqli('HOST', 'USERNAME', 'PASSWORD', 'DATABASE');
Credits to #samuel t thomas

Dynamic SQL queries in code possible?

Instead of hard coding sql queries like Select * from users where user_id =220202 can these be made dynamic like Select * from $users where $user_id = $input.
Reason i ask is when changes are needed to table/column names i can just update it in one place and don't have to ask developers to go line by line to find all references to update. It is very time consuming. And I do not like the idea of exposing database stuff in the code.
My major concern is load time. Like with dynamic pages, the database has to fetch the page content, same way if queries are dynamic first system has to lookup the references then execute the queries, so does it impact load times?
I am using codeignitor PHP.
If it is possible then the next question is where to store all the references? In the app, in a file, in the DB, and how?
---EDIT:
Even better: Can the SQL query itself be made dynamic? I can just reference $sqlA instead of the whole query? This way if I have to re-write the query I can just update 1 file.
Because you are using Codeigniter, I would reccomend utilizing the Active Record Class to accomplish what you are trying to do.
The active record class enables you to build queries dynamically in steps allowing you to build them logically. So to take your example using active record...
( this could be accomplished with less code, I'm just trying to illustrate Active Record )
$this->db->select('*');
$this->db->from($table);
$this->db->where($user_id, $input);
and so to show what I mean about building the query logically, you can build whatever logic you want INTO the query building process. Lets say you have a $limit variable that you set if you want to limit the number of results you get. BUT if it isn't set (or NULL) you don't want to set the limit clause.
if ( $isset($limit) ) {
$this->db->limit($limit);
}
and now to execute your query now that it has been built
$query = $this->db->get();
Then just deal with $query with your database class just like you would any other CodeIgniter query object.
Of course you can, if that's what you wish. I'd rather recommend you taking more time to design you database but changes in the schema are inevitable in the long run.
I don't think load time would be an issue with this because ussually the bottleneck in this applications is in the database.
Finally my recommendation is to save this in a file just by declaring the column names as php variables
It depends on the database driver(s) you are using. The old PHP database drivers did not support placeholders (PHP 3.x). The modern (PDO) ones do. You write the SQL with question marks:
SELECT * FROM Users WHERE User_ID = ?
You then provide the value of the user ID when you execute the query.
However, you cannot provide the column name like this - only values. But you could prepare a statement from a string such as:
SELECT * FROM Users WHERE $user_id = ?
Then you provide the value at execute time.
mysql_query() takes a string and it doesn't need to be a constant string, it can be a variable.
$SQL = "SELECT foo FROM bar b";
SQLSet = mysql_query($SQL);
Aa you can see, you can use ordinary string manipulation to build your whole SQL query.
$SQL="SELECT * FROM MyTable";
$BuzID = 5;
$Filter = "Buz=".$BuzID;
if (is_numeric($BuzID)) SQL .= " WHERE ".$Filter;
SQLSet = mysql_query($SQL);
This will expand to "SELECT * FROM MyTable WHERE Buz=5" if $BuzID is set to any number.
If not the statement will just be "SELECT * FROM MyTable"
As you can see, you can build very complex SQL statements on the fly without need of variable support in the SQL server.
IF you want constants such as database name, user login, you can but them in a separate include located outside the public directory.
SecretStuff.inc.php
$__DatabaseName = "localhost";
$__UserName = "DatabaseAccess";
$__Password = "E19A4F72B4AA091C6D2";
Or have the whole PHP database connection code in the same file.

Categories