here my problem, i’m using asp.net for my site, i get a list of books and show them, all is ok. now i try to sort this books by title, author or other attribute, i’m using this code:
public static IDataReader GetPageByCritere(
int pageNumber,
int pageSize,
out int totalPages,
string critere,
string direction)
{
int pageLowerBound = (pageSize * pageNumber) - pageSize;
totalPages = 1;
int totalRows = GetCount();
if (pageSize > 0) totalPages = totalRows / pageSize;
if (totalRows <= pageSize)
{
totalPages = 1;
}
else
{
int remainder;
Math.DivRem(totalRows, pageSize, out remainder);
if (remainder > 0)
{
totalPages += 1;
}
}
StringBuilder sqlCommand = new StringBuilder();
sqlCommand.Append("SELECT * ");
sqlCommand.Append("FROM a_book ");
//sqlCommand.Append("WHERE ");
sqlCommand.Append("ORDER BY ?Critere ?direction ");
sqlCommand.Append("LIMIT ?PageSize ");
if (pageNumber > 1)
{
sqlCommand.Append("OFFSET ?OffsetRows ");
}
sqlCommand.Append(";");
MySqlParameter[] arParams = new MySqlParameter[4];
arParams[0] = new MySqlParameter("?PageSize", MySqlDbType.Int32);
arParams[0].Direction = ParameterDirection.Input;
arParams[0].Value = pageSize;
arParams[1] = new MySqlParameter("?OffsetRows", MySqlDbType.Int32);
arParams[1].Direction = ParameterDirection.Input;
arParams[1].Value = pageLowerBound;
arParams[2] = new MySqlParameter("?Critere", MySqlDbType.VarChar, 50);
arParams[2].Direction = ParameterDirection.Input;
arParams[2].Value = critere;
arParams[3] = new MySqlParameter("?direction", MySqlDbType.VarChar, 50);
arParams[3].Direction = ParameterDirection.Input;
arParams[3].Value = direction;
return MySqlHelper.ExecuteReader(
GetReadConnectionString(),
sqlCommand.ToString(),
arParams);
}
}
when i execute this code the books don’t get sorted, i get the first items list not sorted, here my sqlCommand and arParams for sorting with title for exemple :
sqlCommand
{SELECT * FROM a_book ORDER BY ?Critere ?direction LIMIT ?PageSize ;}
arParams :
{?PageSize} : 20 {?OffsetRows} : -20 {?Critere} title {?direction} DESC
please help, i didn’t find any solution.
Unfortunately, this used to work in MySql but then the behaviour changed – see http://bugs.mysql.com/bug.php?id=31474. It now behaves like Oracle and SQL Server in this respect.
Instead, you might want to consider building up your order by based on the criteria – hopefully, your critere string is not entered by a user or sourced from user input otherwise you’ll have to guard against SQL Injection.
If your criteria consists of a single column, then you can simply do something like:
If Critere is multi columned then you might want to consider passing your sorting criteria as a list of column-direction.
This is also covered here: Parameter in order by clause doesn't order -mysql, C#