What are the technical reasons for why one shouldn’t use mysql_* functions? (e.g. mysql_query(), mysql_connect() or mysql_real_escape_string())? Why should I use something else even if they work on my site? If they don’t work on my site, why do I get errors like Warning: mysql_connect(): No such file or ...
Many people just use a tool like MSExcel, OpenOffice or other spreadsheet-tools for this purpose. This is a valid solution, just copy the data over there and use the tools the GUI offer to solve this. But... this wasn't the question, and it might even lead to some disadvantages, like how to get theRead more
Many people just use a tool like MSExcel, OpenOffice or other spreadsheet-tools for this purpose. This is a valid solution, just copy the data over there and use the tools the GUI offer to solve this.
But… this wasn’t the question, and it might even lead to some disadvantages, like how to get the data into the spreadsheet, problematic scaling and so on.
The SQL way…
Given his table looks something like this:
CREATE TABLE `test_pivot` (
`pid` bigint(20) NOT NULL AUTO_INCREMENT,
`company_name` varchar(32) DEFAULT NULL,
`action` varchar(16) DEFAULT NULL,
`pagecount` bigint(20) DEFAULT NULL,
PRIMARY KEY (`pid`)
) ENGINE=MyISAM;
Now look into his/her desired table:
company_name EMAIL PRINT 1 pages PRINT 2 pages PRINT 3 pages
-------------------------------------------------------------
CompanyA 0 0 1 3
CompanyB 1 1 2 0
The rows (EMAIL
, PRINT x pages
) resemble conditions. The main grouping is by company_name
.
In order to set up the conditions this rather shouts for using the CASE
-statement. In order to group by something, well, use … GROUP BY
.
The basic SQL providing this pivot can look something like this:
SELECT P.`company_name`,
COUNT(
CASE
WHEN P.`action`='EMAIL'
THEN 1
ELSE NULL
END
) AS 'EMAIL',
COUNT(
CASE
WHEN P.`action`='PRINT' AND P.`pagecount` = '1'
THEN P.`pagecount`
ELSE NULL
END
) AS 'PRINT 1 pages',
COUNT(
CASE
WHEN P.`action`='PRINT' AND P.`pagecount` = '2'
THEN P.`pagecount`
ELSE NULL
END
) AS 'PRINT 2 pages',
COUNT(
CASE
WHEN P.`action`='PRINT' AND P.`pagecount` = '3'
THEN P.`pagecount`
ELSE NULL
END
) AS 'PRINT 3 pages'
FROM test_pivot P
GROUP BY P.`company_name`;
This should provide the desired result very fast. The major downside for this approach, the more rows you want in your pivot table, the more conditions you need to define in your SQL statement.
This can be dealt with, too, therefore people tend to use prepared statements, routines, counters and such.
Some additional links about this topic:
- http://anothermysqldba.blogspot.de/2013/06/pivot-tables-example-in-mysql.html
- http://www.codeproject.com/Articles/363339/Cross-Tabulation-Pivot-Tables-with-MySQL
- http://datacharmer.org/downloads/pivot_tables_mysql_5.pdf
- https://codingsight.com/pivot-tables-in-mysql/
PHP offers three different APIs to connect to MySQL. These are the mysql(removed as of PHP 7), mysqli, and PDO extensions. The mysql_* functions used to be very popular, but their use is not encouraged anymore. The documentation team is discussing the database security situation, and educating usersRead more
PHP offers three different APIs to connect to MySQL. These are the
mysql
(removed as of PHP 7),mysqli
, andPDO
extensions.The
mysql_*
functions used to be very popular, but their use is not encouraged anymore. The documentation team is discussing the database security situation, and educating users to move away from the commonly used ext/mysql extension is part of this (check php.internals: deprecating ext/mysql).And the later PHP developer team has taken the decision to generate
E_DEPRECATED
errors when users connect to MySQL, whether throughmysql_connect()
,mysql_pconnect()
or the implicit connection functionality built intoext/mysql
.ext/mysql
was officially deprecated as of PHP 5.5 and has been removed as of PHP 7.See the Red Box?
When you go on any
mysql_*
function manual page, you see a red box, explaining it should not be used anymore.Why
Moving away from
ext/mysql
is not only about security, but also about having access to all the features of the MySQL database.ext/mysql
was built for MySQL 3.23 and only got very few additions since then while mostly keeping compatibility with this old version which makes the code a bit harder to maintain. Missing features that is not supported byext/mysql
include: (from PHP manual).Reason to not use
mysql_*
function:Above point quoted from Quentin’s answer
Lack of support for prepared statements is particularly important as they provide a clearer, less error prone method of escaping and quoting external data than manually escaping it with a separate function call.
See the comparison of SQL extensions.
Suppressing deprecation warnings
While code is being converted to
MySQLi
/PDO
,E_DEPRECATED
errors can be suppressed by settingerror_reporting
in php.ini to excludeE_DEPRECATED:
Note that this will also hide other deprecation warnings, which, however, may be for things other than MySQL. (from PHP manual)
The article PDO vs. MySQLi: Which Should You Use? by Dejan Marjanovic will help you to choose.
And a better way is
PDO
, and I am now writing a simplePDO
tutorial.A simple and short PDO tutorial
Q. First question in my mind was: what is `PDO`?
A. “PDO – PHP Data Objects – is a database access layer providing a uniform method of access to multiple databases.”
Connecting to MySQL
With
mysql_*
function or we can say it the old way (deprecated in PHP 5.5 and above)With
PDO
: All you need to do is create a newPDO
object. The constructor accepts parameters for specifying the database sourcePDO
‘s constructor mostly takes four parameters which areDSN
(data source name) and optionallyusername
,password
.Here I think you are familiar with all except
DSN
; this is new inPDO
. ADSN
is basically a string of options that tellPDO
which driver to use, and connection details. For further reference, check PDO MySQL DSN.Note: you can also use
charset=UTF-8
, but sometimes it causes an error, so it’s better to useutf8
.If there is any connection error, it will throw a
PDOException
object that can be caught to handleException
further.Good read: Connections and Connection management ¶
You can also pass in several driver options as an array to the fourth parameter. I recommend passing the parameter which puts
PDO
into exception mode. Because somePDO
drivers don’t support native prepared statements, soPDO
performs emulation of the prepare. It also lets you manually enable this emulation. To use the native server-side prepared statements, you should explicitly set itfalse
.The other is to turn off prepare emulation which is enabled in the
MySQL
driver by default, but prepare emulation should be turned off to usePDO
safely.I will later explain why prepare emulation should be turned off. To find reason please check this post.
It is only usable if you are using an old version of
MySQL
which I do not recommended.Below is an example of how you can do it:
Can we set attributes after PDO construction?
Yes, we can also set some attributes after PDO construction with the
setAttribute
method:Error Handling
Error handling is much easier in
PDO
thanmysql_*
.A common practice when using
mysql_*
is:OR die()
is not a good way to handle the error since we can not handle the thing indie
. It will just end the script abruptly and then echo the error to the screen which you usually do NOT want to show to your end users, and let bloody hackers discover your schema. Alternately, the return values ofmysql_*
functions can often be used in conjunction with mysql_error() to handle errors.PDO
offers a better solution: exceptions. Anything we do withPDO
should be wrapped in atry
–catch
block. We can forcePDO
into one of three error modes by setting the error mode attribute. Three error handling modes are below.PDO::ERRMODE_SILENT
. It’s just setting error codes and acts pretty much the same asmysql_*
where you must check each result and then look at$db->errorInfo();
to get the error details.PDO::ERRMODE_WARNING
RaiseE_WARNING
. (Run-time warnings (non-fatal errors). Execution of the script is not halted.)PDO::ERRMODE_EXCEPTION
: Throw exceptions. It represents an error raised by PDO. You should not throw aPDOException
from your own code. See Exceptions for more information about exceptions in PHP. It acts very much likeor die(mysql_error());
, when it isn’t caught. But unlikeor die()
, thePDOException
can be caught and handled gracefully if you choose to do so.Good read:
Like:
And you can wrap it in
try
–catch
, like below:You do not have to handle with
try
–catch
right now. You can catch it at any time appropriate, but I strongly recommend you to usetry
–catch
. Also it may make more sense to catch it at outside the function that calls thePDO
stuff:Also, you can handle by
or die()
or we can say likemysql_*
, but it will be really varied. You can hide the dangerous error messages in production by turningdisplay_errors off
and just reading your error log.Now, after reading all the things above, you are probably thinking: what the heck is that when I just want to start leaning simple
SELECT
,INSERT
,UPDATE
, orDELETE
statements? Don’t worry, here we go:Selecting Data
So what you are doing in
mysql_*
is:Now in
PDO
, you can do this like:Or
Note: If you are using the method like below (
query()
), this method returns aPDOStatement
object. So if you want to fetch the result, use it like above.In PDO Data, it is obtained via the
->fetch()
, a method of your statement handle. Before calling fetch, the best approach would be telling PDO how you’d like the data to be fetched. In the below section I am explaining this.Fetch Modes
Note the use of
PDO::FETCH_ASSOC
in thefetch()
andfetchAll()
code above. This tellsPDO
to return the rows as an associative array with the field names as keys. There are many other fetch modes too which I will explain one by one.First of all, I explain how to select fetch mode:
In the above, I have been using
fetch()
. You can also use:PDOStatement::fetchAll()
– Returns an array containing all of the result set rowsPDOStatement::fetchColumn()
– Returns a single column from the next row of a result setPDOStatement::fetchObject()
– Fetches the next row and returns it as an object.PDOStatement::setFetchMode()
– Set the default fetch mode for this statementNow I come to fetch mode:
PDO::FETCH_ASSOC
: returns an array indexed by column name as returned in your result setPDO::FETCH_BOTH
(default): returns an array indexed by both column name and 0-indexed column number as returned in your result setThere are even more choices! Read about them all in
PDOStatement
Fetch documentation..Getting the row count:
Instead of using
mysql_num_rows
to get the number of returned rows, you can get aPDOStatement
and dorowCount()
, like:Getting the Last Inserted ID
Insert and Update or Delete statements
What we are doing in
mysql_*
function is:And in pdo, this same thing can be done by:
In the above query
PDO::exec
execute an SQL statement and returns the number of affected rows.Insert and delete will be covered later.
The above method is only useful when you are not using variable in query. But when you need to use a variable in a query, do not ever ever try like the above and there for prepared statement or parameterized statement is.
Prepared Statements
Q. What is a prepared statement and why do I need them?
A. A prepared statement is a pre-compiled SQL statement that can be executed multiple times by sending only the data to the server.
The typical workflow of using a prepared statement is as follows (quoted from Wikipedia three 3 point):
?
below):1.00
for the second parameter.You can use a prepared statement by including placeholders in your SQL. There are basically three ones without placeholders (don’t try this with variable its above one), one with unnamed placeholders, and one with named placeholders.
Q. So now, what are named placeholders and how do I use them?
A. Named placeholders. Use descriptive names preceded by a colon, instead of question marks. We don’t care about position/order of value in name place holder:
bindParam(parameter,variable,data_type,length,driver_options)
You can also bind using an execute array as well:
Another nice feature for
OOP
friends is that named placeholders have the ability to insert objects directly into your database, assuming the properties match the named fields. For example:Q. So now, what are unnamed placeholders and how do I use them?
A. Let’s have an example:
and
In the above, you can see those
?
instead of a name like in a name place holder. Now in the first example, we assign variables to the various placeholders ($stmt->bindValue(1, $name, PDO::PARAM_STR);
). Then, we assign values to those placeholders and execute the statement. In the second example, the first array element goes to the first?
and the second to the second?
.NOTE: In unnamed placeholders we must take care of the proper order of the elements in the array that we are passing to the
PDOStatement::execute()
method.SELECT
,INSERT
,UPDATE
,DELETE
prepared queriesSELECT
:$stmt = $db->prepare(“SELECT * FROM table WHERE id=:id AND name=:name”); $stmt->execute(array(‘:name’ => $name, ‘:id’ => $id)); $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
INSERT
:$stmt = $db->prepare(“INSERT INTO table(field1,field2) VALUES(:field1,:field2)”); $stmt->execute(array(‘:field1’ => $field1, ‘:field2’ => $field2)); $affected_rows = $stmt->rowCount();
DELETE
:$stmt = $db->prepare(“DELETE FROM table WHERE id=:id”); $stmt->bindValue(‘:id’, $id, PDO::PARAM_STR); $stmt->execute(); $affected_rows = $stmt->rowCount();
UPDATE
:$stmt = $db->prepare(“UPDATE table SET name=? WHERE id=?”); $stmt->execute(array($name, $id)); $affected_rows = $stmt->rowCount();
NOTE:
However
See lessPDO
and/orMySQLi
are not completely safe. Check the answer Are PDO prepared statements sufficient to prevent SQL injection? by ircmaxell. Also, I am quoting some part from his answer: