I’ve form elements named in ascending order such as
<input type="text" name="v1[abc]" />
<input type="text" name="v2[abc]" />
<input type="text" name="v3[abc]" />
<input type="text" name="v4[abc]" />
I’m processing these values using
for($i = 1; $i <= 4; $i++) {
$v = $_POST['v'.$i];
insert('tablename', $v);
}
Below is the insert function being used
function insert($tableName, $array) {
array_map( 'mysql_real_escape_string', $array );
$qry = mysql_query("INSERT INTO ".$tableName." ( ". implode( ',', array_keys( $array) ) .") VALUES( '". implode( "','", $array ) . "')");
if(! $qry) {
die(mysql_error());
}
}
If I enter 1 inside the first textbox, 2 inside the second textbox and so on, after insertion this is what I get in my table
----
abc |
----
4 |
3 |
2 |
1 |
----
This is quite baffling and I’m not able to find out why this is happening. This is important to me because I want the values to be inserted in the same order that they were entered.
It’s kind of hard to explain the reason behind the enter in the same order requirement but are there any possible reasons as to why the data is being entered in the descending order?
Your assumption that tables have order is wrong. You get the order you want when you retrieve data by using the
ORDER BYSQL clause. Otherwise, tables are unsorted.Update: Yep, in the end, databases are nothing but files. But the exact algorithm that MySQL follows to write on disk sectors can only be guessed by looking at the C source code, although I can figure out what the general guideline is: put stuff where you think it’ll be faster to do. When you do a
SELECTwithoutORDER BYyou tend to obtain the same apparent order but it’s only because it wouldn’t make sense for MySQL to waste resources trying to sort or randomize the rows for no good reason. A simpleOPTIMIZE TABLEcan alter this row order.