Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
How to configure port for a Spring Boot application?
Option 1: s said in docs either set server.port as system property using command line option to jvm -Dserver.port=8090 or add application.properties in /src/main/resources/ with server.port=8090 For a random port use: server.port=0 Similarly add application.yml in /src/main/resources/ with: server:Read more
Option 1:
s said in docs either set
server.port
as system property using command line option to jvm-Dserver.port=8090
or addapplication.properties
in/src/main/resources/
withFor a random port use:
Similarly add
application.yml
in/src/main/resources/
with:Option 2:
You can configure the port programmatically.
For Spring Boot 2.x.x:
For older versions:
See lessHow to access a value defined in the application.properties file in Spring Boot
Option 1: You can use the @Value annotation and access the property in whichever Spring bean you're using @Value("${userBucket.path}") private String userBucketPath; The Externalized Configuration section of the Spring Boot docs, explains all the details that you might need. Option 2: AnotherRead more
Option 1:
You can use the
@Value
annotation and access the property in whichever Spring bean you’re usingThe Externalized Configuration section of the Spring Boot docs, explains all the details that you might need.
Option 2:
Another way is injecting
See lessorg.springframework.core.env.Environment
to your bean.How to delete an element from an array in PHP?
There are different ways to delete an array element, where some are more useful for some specific tasks than others. Deleting a Single Array Element If you want to delete just one single array element you can use unset() and alternatively array_splice(). By key or by value? If you know the value andRead more
There are different ways to delete an array element, where some are more useful for some specific tasks than others.
Deleting a Single Array Element
If you want to delete just one single array element you can use
unset()
and alternativelyarray_splice()
.By key or by value?
If you know the value and don’t know the key to delete the element you can use
array_search()
to get the key. This only works if the element doesn’t occur more than once, sincearray_search()
returns the first hit only.unset()
ExpressionNote: When you use
unset()
the array keys won’t change. If you want to reindex the keys you can usearray_values()
afterunset()
, which will convert all keys to numerically enumerated keys starting from 0 (the array remains a list).Example Code:
Example Output:
array_splice()
FunctionIf you use
array_splice()
the (integer) keys will automatically be reindex-ed, but the associative (string) keys won’t change — as opposed toarray_values()
afterunset()
, which will convert all keys to numerical keys.Note:
array_splice()
needs the offset, not the key, as the second parameter; offset= array_flip(array_keys(
array))[
key]
.Example Code:
Example Output:
array_splice()
, same asunset()
, take the array by reference. You don’t assign the return values back to the array.Deleting Multiple Array Elements
If you want to delete multiple array elements and don’t want to call
unset()
orarray_splice()
multiple times you can use the functionsarray_diff()
orarray_diff_key()
depending on whether you know the values or the keys of the elements to remove from the array.array_diff()
FunctionIf you know the values of the array elements which you want to delete, then you can use
array_diff()
. As before withunset()
it won’t change the keys of the array.Example Code:
Example Output:
array_diff_key()
FunctionIf you know the keys of the elements which you want to delete, then you want to use
array_diff_key()
. You have to make sure you pass the keys as keys in the second parameter and not as values. Keys won’t reindex.Example Code:
Example Output:
If you want to use
unset()
orarray_splice()
to delete multiple elements with the same value you can usearray_keys()
to get all the keys for a specific value and then delete all elements.array_filter()
FunctionIf you want to delete all elements with a specific value in the array you can use
array_filter()
.Example Code:
Example Output:
See lessWhy to not use mysql_* functions in PHP?
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:How to avoid checking for nulls in Java?
This to me sounds like a reasonably common problem that junior to intermediate developers tend to face at some point: they either don't know or don't trust the contracts they are participating in and defensively overcheck for nulls. Additionally, when writing their own code, they tend to rely on retRead more
This to me sounds like a reasonably common problem that junior to intermediate developers tend to face at some point: they either don’t know or don’t trust the contracts they are participating in and defensively overcheck for nulls. Additionally, when writing their own code, they tend to rely on returning nulls to indicate something thus requiring the caller to check for nulls.
To put this another way, there are two instances where null checking comes up:
(2) is easy. As of Java 1.7 you can use
Objects.requireNonNull(foo)
. (If you are stuck with a previous version thenassert
ions may be a good alternative.)“Proper” usage of this method would be like below. The method returns the object passed into it and throws a
NullPointerException
if the object is null. This means that the returned value is always non-null. The method is primarily intended for validating parameters.It can also be used like an
assert
ion though since it throws an exception if the object is null. In both uses, a message can be added which will be shown in the exception. Below is using it like an assertion and providing a message.Generally throwing a specific exception like
NullPointerException
when a value is null but shouldn’t be is favorable to throwing a more general exception likeAssertionError
. This is the approach the Java library takes; favoringNullPointerException
overIllegalArgumentException
when an argument is not allowed to be null.(1) is a little harder. If you have no control over the code you’re calling then you’re stuck. If null is a valid response, you have to check for it.
If it’s code that you do control, however (and this is often the case), then it’s a different story. Avoid using nulls as a response. With methods that return collections, it’s easy: return empty collections (or arrays) instead of nulls pretty much all the time.
With non-collections it might be harder. Consider this as an example: if you have these interfaces:
where Parser takes raw user input and finds something to do, perhaps if you’re implementing a command line interface for something. Now you might make the contract that it returns null if there’s no appropriate action. That leads the null checking you’re talking about.
An alternative solution is to never return null and instead use the Null Object pattern:
Compare:
to
which is a much better design because it leads to more concise code.
That said, perhaps it is entirely appropriate for the findAction() method to throw an Exception with a meaningful error message — especially in this case where you are relying on user input. It would be much better for the findAction method to throw an Exception than for the calling method to blow up with a simple NullPointerException with no explanation.
Or if you think the try/catch mechanism is too ugly, rather than Do Nothing your default action should provide feedback to the user.
See lessHow to efficiently iterate over each entry in a Java Map?
To summarize the other answers and combine them with what I know, I found 10 main ways to do this (see below). Also, I wrote some performance tests (see results below). For example, if we want to find the sum of all of the keys and values of a map, we can write: Using iterator and Map.Entry long i =Read more
To summarize the other answers and combine them with what I know, I found 10 main ways to do this (see below). Also, I wrote some performance tests (see results below). For example, if we want to find the sum of all of the keys and values of a map, we can write:
Apache Collections
Perfomance tests (mode = AverageTime, system = Windows 8.1 64-bit, Intel i7-4790 3.60 GHz, 16 GB)
Graphs (performance tests depending on map size)
Table (perfomance tests depending on map size)
See lessHow to read / convert an InputStream into a String in Java?
To summarize the other answers, I found 11 main ways to do this (see below). And I wrote some performance tests (see results below): Ways to convert an InputStream to a String: Using IOUtils.toString (Apache Utils) String result = IOUtils.toString(inputStream, StandardCharsets.UTF_8); Using CharStreRead more
To summarize the other answers, I found 11 main ways to do this (see below). And I wrote some performance tests (see results below):
Ways to convert an InputStream to a String:
IOUtils.toString
(Apache Utils)CharStreams
(Guava)Scanner
(JDK)\r\n
) to\n
.\r\n
) to\n
.InputStreamReader
andStringBuilder
(JDK)StringWriter
andIOUtils.copy
(Apache Commons)ByteArrayOutputStream
andinputStream.read
(JDK)BufferedReader
(JDK). Warning: This solution converts different line breaks (like\n\r
) toline.separator
system property (for example, in Windows to “\r\n”).BufferedInputStream
andByteArrayOutputStream
(JDK)inputStream.read()
andStringBuilder
(JDK). Warning: This solution has problems with Unicode, for example with Russian text (works correctly only with non-Unicode text)Warning:
Performance tests
Performance tests for small
String
(length = 175), url in github (mode = Average Time, system = Linux, score 1,343 is the best):Performance tests for big
String
(length = 50100), url in github (mode = Average Time, system = Linux, score 200,715 is the best):Graphs (performance tests depending on Input Stream length in Windows 7 system)
Performance test (Average Time) depending on Input Stream length in Windows 7 system:
See less