/    Sign up×
Community /Pin to ProfileBookmark

Why does MySQL database start at zero but give the first record an ID of 1?

I’m just starting to learn about how to use MySQL database. I insert data using the code that is listed below. It puts the first record in as record 0, but when I look at it, it says it has and ID# of 1. I have it set to autoincrement.

What am I missing?

Here is my code to insert it:

[code=php]

<?php
// Inserts question into drmarie_questions MySQL database
$ownername=$_POST[‘ownername’];
$petname=$_POST[‘petname’];
$species=$_POST[‘species’];
$breed=$_POST[‘breed’];
$age=$_POST[‘age’];
$email=$_POST[’email’];
$question=$_POST[‘question’];

mysql_connect(“localhost”, “deleted”, “deleted”) or die(mysql_error());
mysql_select_db(“drmarie_questions”) or die(mysql_error());
mysql_query(“INSERT INTO question_table (ownername,petname,species,breed,age,email,question)
VALUES (‘$ownername’,’$petname’,’$species’,’$breed’,’$age’,’$email’,’$question’)”) or die(mysql_error());

mysql_close();

?>
[/code]

If anyone can point me in the right direction I would be very appreciative!

Thanks!
Marie

to post a comment
PHP

11 Comments(s)

Copy linkTweet thisAlerts:
@SyCoMay 19.2009 — If you don't provide an index when creating an array then it assigns an index start of 0.

[code=php]$my_array[]='hello';
echo $my_array[0];[/code]


A SQL id start at 1 because it's the first record.

A couple of comments on your code

[code=php]$ownername=$_POST['ownername'];[/code]

You'll see people do this a lot but it serves no purpose.

This make sense,
[code=php]$ownername=trim($_POST['ownername']);[/code]

as you're processing the variable but there is no point renaming a variable for no reason.

When a script gets big and complex it's good to know where the vars came from. A POST var is direct user input so should be considered dangerous and suspect. In fact anytime you collect data from a user you need to make sure there is no way to damage you server. Currently your script is vulnerable to a type of attack called SQL injection. Google that term and read up. It's easy to secure a SQL query against this kind of attack but it's important you understand it.

So if you don't rename the vars you can clearly see $_POST['ownername'] needs to be secured but does $ownername? You'll have to back track through a script to find out. It just increase the likelyhood of a mistake.

When you're debugging POST stuff it's useful to print_r($_POST) at teh top of the page to see if you're getting the variables you expected. Often a type in an input name is to blame and it's obvious that the var is empty if you print the array. Wrap it in <pre> tags to get a nicer format.
Copy linkTweet thisAlerts:
@DrMarieauthorMay 19.2009 — Thanks so much for your reply...I just have a couple of questions:

How do I start my SQL at 1 instead of 0? I had originally set up the database with myPHP.

I do plan to make my SQL stuff more secure but at first I am just trying to understand the programming of it and then I will dive into making it secure.

The variable 'ownername' comes from a form that was filled out. Don't I have to use $_POST if I am getting info from a form and trying to put it into a database?

Thanks!

Marie
Copy linkTweet thisAlerts:
@MindzaiMay 19.2009 — What SyCo is saying is that you can use $_POST['ownername'] directly - it is already a variable, all you are doing in your script is duplicating it for no reason.

Regarding the 1 and 0, i'm not sure I fully understand the problem, but programmers tend to count from 0, so row 0 = the first row. However MySQL gives the first record an id of 1 because (amongst other reasons I assume), data is intended to be read by humans not programmers :p so an ID of 0 would probably seem odd to most people.

About the security, I hear that all the time, and I understand why you would want to get something working then secure it later, but imo you are better off not viewing security as something to be tacked on later. If you are going to learn to program (in PHP especially) you really need to understand the best practices regarding security and code with them in mind all the time.
Copy linkTweet thisAlerts:
@DrMarieauthorMay 19.2009 — My problem with the SQL database is that the first record has an id of 1, but when I go to retrieve it, it is actually record 0. It's not a big deal...I can easily tell my program to search for id-1 but it just seems like there is something I am missing.

I'll start looking at the security options in the next couple of days. Thanks for helping me to be a good programmer!
Copy linkTweet thisAlerts:
@NogDogMay 19.2009 — Do not confuse "record number" with the value in an integer field which is being used as the primary key for that table. You could conceivably delete the first 5 records from that table, such that the lowest-numbered key field would now be have a "6" as its value. If you then did a [b]SELECT * FROM that_table ORDER BY primary_key_column[/b], the first row returned in the result set (which PHP would consider row 0), would have an ID value of 6.

On top of all of that, the sequence in which the records are stored by the database on disk is not necessarily going to be the same as the sequence of that key field. So my best advice is to simply stop thinking of the database records (rows) being in any specific order unless and until you specifically order them via an ORDER BY or GROUP BY clause in your query; and divorce that sequence in your mind from the arbitrary number of [i]result set[/i] rows returned by any query. (For instance, [b]SELECT * FROM table WHERE color='blue' ORDER BY id[/b] might return rows with ID number 5,7,8,9,12,15, and 18, but the [i]result set row numbers[/i] would be 0-6.)
Copy linkTweet thisAlerts:
@DrMarieauthorMay 19.2009 — Ah oh...so I will ignore the record number and just concentrate on the ID for now. Thanks...I am slowly getting this! And again...all of you guys are amazing.
Copy linkTweet thisAlerts:
@DrMarieauthorMay 19.2009 — AAARGH...I cannot figure this out. Look at this code:

[code=php]
<?
$username="deleted";
$password="deleted";
$database="deleted";
$i=1;

mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");
$query="SELECT * FROM question_table";
$result=mysql_query($query);



mysql_close();




$ownername=mysql_result($result,$i,"ownername");
$petname=mysql_result($result,$i,"petname");
$species=mysql_result($result,$i,"species");
$age=mysql_result($result,$i,"age");
$breed=mysql_result ($result,$i,"breed");
$question=mysql_result ($result,$i,"question");




[/code]


It doesn't seem to work without the $i...and the $i doesn't always match the ID. I tried doing this:

[code=php]
$query="SELECT * FROM question_table WHERE id=1";
[/code]


...but it gives me an error that that record can't be found. The database definitely has records in it and there is one with an id of 1.

Can someone help? All I want to do is to select one record based on its id number. I have been stuck for 2 days on this!!!
Copy linkTweet thisAlerts:
@DrMarieauthorMay 19.2009 — OK, I think I got it...instead of putting $i in my mysql_result strings, I just need to use 0 each time. It seems to work that way.
Copy linkTweet thisAlerts:
@MindzaiMay 19.2009 — You would be better doing this

[code=php]
if (!$row = mysql_fetch_assoc($result)) {
die ('couldn't get row');
}
extract($row);
echo $ownername; // etc
[/code]


Or even just:

[code=php]
if (!$row = mysql_fetch_assoc($result)) {
die ('couldn't get row');
}
echo $row['ownername']; // etc
[/code]


mysql_result is only really useful where you just want one specific field's data. Otherwise it's much more straightforward just to grab the whole row and stick it in an array or an object.
Copy linkTweet thisAlerts:
@DrMarieauthorMay 19.2009 — I thought it should have been way simpler than what I was doing! I'll try that and see how it goes. Thanks!

Marie
Copy linkTweet thisAlerts:
@NogDogMay 19.2009 — Another advantage of mysql_fetch_assoc() is that it's not affected if you change the order of the columns being selected in your query or if you do a "SELECT *" and the database table's column sequence is altered in any way. Also, it makes it easier when reading the code to immediately see which column you are working with at any particular point, e.g. with [b]$row['color'][/b] you know right away what the variable represents, whereas [b]$row[1][/b] or [b]mysql_result($ix, 1)[/b] is not obvious.
×

Success!

Help @DrMarie spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.2,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,
)...