Questions tagged [mysql]

MySQL is a free, open-source Relational Database Management System (RDBMS) that uses Structured Query Language (SQL). DO NOT USE this tag for other DBs such as SQL Server, SQLite etc. Those are different DBs that all use their own dialects of SQL to manage the data. Always specify the exact version of the server in the question. Versions 5.x differ greatly in their capabilities from versions 8+.

Filter by
Sorted by
Tagged with
2773 votes
27 answers
2.1m views

How can I prevent SQL injection in PHP?

If user input is inserted without modification into an SQL query, then the application becomes vulnerable to SQL injection, like in the following example: $unsafe_variable = $_POST['user_input']; ...
2696 votes
14 answers
254k views

Why shouldn't I use mysql_* functions in PHP?

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 ...
1332 votes
13 answers
197k views

UTF-8 all the way through

I'm setting up a new server and want to support UTF-8 fully in my web application. I have tried this in the past on existing servers and always seem to end up having to fall back to ISO-8859-1. Where ...
  • 22k
762 votes
13 answers
287k views

When to use single quotes, double quotes, and backticks in MySQL

I am trying to learn the best way to write queries. I also understand the importance of being consistent. Until now, I have randomly used single quotes, double quotes, and backticks without any real ...
  • 25.7k
760 votes
4 answers
301k views

SQL injection that gets around mysql_real_escape_string()

Is there an SQL injection possibility even when using mysql_real_escape_string() function? Consider this sample situation. SQL is constructed in PHP like this: $login = mysql_real_escape_string(...
  • 79.8k
1600 votes
27 answers
1.9m views

SQL select only rows with max value on a column [duplicate]

I have this table for documents (simplified version here): id rev content 1 1 ... 2 1 ... 1 2 ... 1 3 ... How do I select one row per id and only the greatest rev? With the above data, the ...
117 votes
4 answers
17k views

Can I mix MySQL APIs in PHP?

I have searched the net and so far what I have seen is that you can use mysql_ and mysqli_ together meaning: <?php $con=mysqli_connect("localhost", "root" ,"" ,"mysql"); if( mysqli_connect_errno( ...
  • 1,363
48 votes
1 answer
209k views

Syntax error due to using a reserved word as a table or column name in MySQL

I'm trying to execute a simple MySQL query as below: INSERT INTO user_details (username, location, key) VALUES ('Tim', 'Florida', 42) But I'm getting the following error: ERROR 1064 (42000): You ...
378 votes
10 answers
461k views

How can I return pivot table output in MySQL?

If I have a MySQL table looking something like this: company_name action pagecount ------------------------------- Company A PRINT 3 Company A PRINT 2 Company A PRINT 3 ...
  • 4,943
108 votes
5 answers
94k views

Trouble with UTF-8 characters; what I see is not what I stored

I tried to use UTF-8 and ran into trouble. I have tried so many things; here are the results I have gotten: ???? instead of Asian characters. Even for European text, I got Se?or for Señor. Strange ...
  • 132k
1283 votes
33 answers
1.1m views

Retrieving the last record in each group - MySQL

There is a table messages that contains data as shown below: Id Name Other_Columns ------------------------- 1 A A_data_1 2 A A_data_2 3 A A_data_3 4 B ...
  • 26.7k
360 votes
14 answers
739k views

Connect Java to a MySQL database

How do you connect to a MySQL database in Java? When I try, I get java.sql.SQLException: No suitable driver found for jdbc:mysql://database/table at java.sql.DriverManager.getConnection(...
  • 9,100
1003 votes
31 answers
775k views

mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource

I am trying to select data from a MySQL table, but I get one of the following error messages: mysql_fetch_array() expects parameter 1 to be resource, boolean given This is my code: $username = $...
  • 24.5k
77 votes
5 answers
436k views

How to include a PHP variable inside a MySQL statement

I'm trying to insert values in the contents table. It works fine if I do not have a PHP variable inside VALUES. When I put the variable $type inside VALUES then this doesn't work. What am I doing ...
  • 10k
425 votes
16 answers
422k views

How to create a MySQL hierarchical recursive query?

I have a MySQL table which is as follows: id name parent_id 19 category1 0 20 category2 19 21 category3 20 22 category4 21 ... ... ... Now, I want to have a single MySQL query to which I simply ...
2121 votes
2 answers
2.1m views

What's the difference between INNER JOIN, LEFT JOIN, RIGHT JOIN and FULL JOIN? [duplicate]

What's the difference between INNER JOIN, LEFT JOIN, RIGHT JOIN and FULL JOIN in MySQL?
  • 32.5k
837 votes
15 answers
1.0m views

How can I do a FULL OUTER JOIN in MySQL?

I want to do a full outer join in MySQL. Is this possible? Is a full outer join supported by MySQL?
  • 20.9k
804 votes
16 answers
691k views

MySQL Error 1093 - Can't specify target table for update in FROM clause

I have a table story_category in my database with corrupt entries. The next query returns the corrupt entries: SELECT * FROM story_category WHERE category_id NOT IN ( SELECT DISTINCT category....
92 votes
1 answer
112k views

MySQL pivot row into dynamic number of columns

Lets say I have three different MySQL tables: Table products: id | name 1 Product A 2 Product B Table partners: id | name 1 Partner A 2 Partner B Table sales: partners_id | ...
  • 1,165
504 votes
14 answers
513k views

Using LIMIT within GROUP BY to get N results per group?

The following query: SELECT year, id, rate FROM h WHERE year BETWEEN 2000 AND 2009 AND id IN (SELECT rid FROM table2) GROUP BY id, year ORDER BY id, rate DESC yields: year id rate 2006 p01 8 ...
  • 10.2k
262 votes
13 answers
337k views

MySQL - Rows to Columns

I tried to search posts, but I only found solutions for SQL Server/Access. I need a solution in MySQL (5.X). I have a table (called history) with 3 columns: hostid, itemname, itemvalue. If I do a ...
  • 5,201
40 votes
4 answers
54k views

mysqli or die, does it have to die?

If I use a bit of code like this: $update_result = mysqli_query( $link , $sql_update_login ) or die ('Unable to execute query. '. mysqli_error($link)); Does it have to die or can you put a ...
  • 1,600
311 votes
51 answers
920k views

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

I'm working on getting my database to talk to my Java programs. Can someone give me a quick and dirty sample program using the JDBC? I'm getting a rather stupendous error: Exception in thread "main"...
  • 28.1k
187 votes
12 answers
224k views

Get top n records for each group of grouped results

The following is the simplest possible example, though any solution should be able to scale to however many n top results are needed: Given a table like that below, with person, group, and age ...
  • 170k
521 votes
43 answers
1.7m views

MySQL ERROR 1045 (28000): Access denied for user 'bill'@'localhost' (using password: YES)

First let me mention that I've gone through many suggested questions and found no relevent answer. Here is what I'm doing. I'm connected to my Amazon EC2 instance. I can login with MySQL root with ...
  • 7,622
1455 votes
16 answers
860k views

Can I concatenate multiple MySQL rows into one field?

Using MySQL, I can do something like: SELECT hobbies FROM peoples_hobbies WHERE person_id = 5; My Output: shopping fishing coding but instead I just want 1 row, 1 col: Expected Output: shopping, ...
  • 31.4k
324 votes
26 answers
704k views

ROW_NUMBER() in MySQL

Is there a nice way in MySQL to replicate the SQL Server function ROW_NUMBER()? For example: SELECT col1, col2, ROW_NUMBER() OVER (PARTITION BY col1, col2 ORDER BY col3 DESC) AS intRow ...
  • 16k
13 votes
1 answer
18k views

Is "mysqli_real_escape_string" enough to avoid SQL injection or other SQL attacks?

This is my code: $email= mysqli_real_escape_string($db_con,$_POST['email']); $psw= mysqli_real_escape_string($db_con,$_POST['psw']); $query = "INSERT INTO `users` (`email`,`psw`) VALUES ('".$...
  • 25.2k
48 votes
4 answers
118k views

How to check if a row exists in MySQL? (i.e. check if username or email exists in MySQL)

I need help checking if a row exists in the database. In my case, that row contains an email address. I am getting the result: email no longer exists publisher@example.com This is the code I'm ...
902 votes
22 answers
1.9m views

How can I SELECT rows with MAX(Column value), PARTITION by another column in MYSQL?

I have a table of player performance: CREATE TABLE TopTen ( id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT, home INT UNSIGNED NOT NULL, `datetime`DATETIME NOT NULL, player VARCHAR(6) NOT NULL, ...
  • 9,693
1094 votes
12 answers
698k views

INNER JOIN ON vs WHERE clause

For simplicity, assume all relevant fields are NOT NULL. You can do: SELECT table1.this, table2.that, table2.somethingelse FROM table1, table2 WHERE table1.foreignkey = table2.primarykey ...
  • 15.9k
597 votes
13 answers
592k views

How to do a regular expression replace in MySQL?

I have a table with ~500k rows; varchar(255) UTF8 column filename contains a file name; I'm trying to strip out various strange characters out of the filename - thought I'd use a character class: [^a-...
1052 votes
11 answers
1.0m views

How can I do 'insert if not exists' in MySQL?

I started by googling and found the article How to write INSERT if NOT EXISTS queries in standard SQL which talks about mutex tables. I have a table with ~14 million records. If I want to add more ...
  • 32k
267 votes
25 answers
1.2m views

Solving a "communications link failure" with JDBC and MySQL [duplicate]

I'm trying to connect to the local MySQL server but I keep getting an error. Here is the code. public class Connect { public static void main(String[] args) { Connection conn = null; ...
  • 2,723
501 votes
18 answers
709k views

Error related to only_full_group_by when executing a query in MySql

I have upgraded my system and have installed MySql 5.7.9 with php for a web application I am working on. I have a query that is dynamically created, and when run in older versions of MySQL it works ...
  • 5,265
173 votes
14 answers
326k views

Rank function in MySQL

I need to find out rank of customers. Here I am adding the corresponding ANSI standard SQL query for my requirement. Please help me to convert it to MySQL . SELECT RANK() OVER (PARTITION BY Gender ...
  • 6,861
108 votes
20 answers
140k views

MySQL Creating tables with Foreign Keys giving errno: 150

I am trying to create a table in MySQL with two foreign keys, which reference the primary keys in 2 other tables, but I am getting an errno: 150 error and it will not create the table. Here is the SQL ...
user avatar
97 votes
13 answers
217k views

Project Links do not work on Wamp Server

I am installing the Wamp Server on another computer to run a mid-sized database and UI. I have been successful in blocking IIS and routing the server to Localhost:8080. But whenever I try to access on ...
175 votes
1 answer
395k views

The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead [duplicate]

When I attempt to connect to a MySQL server from PHP, I see the following error: Deprecated: The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in /path/...
  • 121k
438 votes
28 answers
454k views

Remove duplicate rows in MySQL

I have a table with the following fields: id (Unique) url (Unique) title company site_id Now, I need to remove rows having same title, company and site_id. One way to do it will be using the ...
  • 4,845
342 votes
13 answers
148k views

mysqli or PDO - what are the pros and cons? [closed]

In our place we're split between using mysqli and PDO for stuff like prepared statements and transaction support. Some projects use one, some the other. There is little realistic likelihood of us ever ...
  • 22.8k
125 votes
12 answers
270k views

SQL split values to multiple rows

I have table : id | name 1 | a,b,c 2 | b i want output like this : id | name 1 | a 1 | b 1 | c 2 | b
  • 1,291
1066 votes
20 answers
590k views

Join vs. sub-query

I am an old-school MySQL user and have always preferred JOIN over sub-query. But nowadays everyone uses sub-query, and I hate it; I don't know why. I lack the theoretical knowledge to judge for ...
934 votes
12 answers
1.0m views

"INSERT IGNORE" vs "INSERT ... ON DUPLICATE KEY UPDATE"

While executing an INSERT statement with many rows, I want to skip duplicate entries that would otherwise cause failure. After some research, my options appear to be the use of either: ON DUPLICATE ...
465 votes
6 answers
920k views

SQL query return data from multiple tables

I would like to know the following: how to get data from multiple tables in my database? what types of methods are there to do this? what are joins and unions and how are they different from one ...
1125 votes
12 answers
1.2m views

Insert into a MySQL table or update if exists

I want to add a row to a database table, but if a row exists with the same unique key I want to update the row. For example: INSERT INTO table_name (ID, NAME, AGE) VALUES(1, "A", 19); Let’s ...
  • 14.1k
127 votes
11 answers
68k views

How to apply bindValue method in LIMIT clause?

Here is a snapshot of my code: $fetchPictures = $PDO->prepare("SELECT * FROM pictures WHERE album = :albumId ORDER BY id ASC LIMIT :skip, :max"); $fetchPictures->bindValue('...
  • 47.7k
541 votes
28 answers
560k views

MySQL select 10 random rows from 600K rows fast

How can I best write a query that selects 10 rows randomly from a total of 600k?
  • 75.9k
335 votes
19 answers
367k views

Get records with max value for each group of grouped SQL results

How do you get the rows that contain the max value for each grouped set? I've seen some overly-complicated variations on this question, and none with a good answer. I've tried to put together the ...
  • 170k
110 votes
9 answers
93k views

PHP - Using PDO with IN clause array

I'm using PDO to execute a statement with an IN clause that uses an array for its values: $in_array = array(1, 2, 3); $in_values = implode(',', $in_array); $my_result = $wbdb->prepare("SELECT *...
  • 1,915

1
2 3 4 5
909