Log in

View Full Version : MYSQL Query Shortened



bluewalrus
02-19-2011, 07:47 PM
I just started using MYSQL so I'm not sure if I've done something wrong here. The data went into the database but the first character of the first query was removed.

I executed this query in PHP and it inserted into the database but the first value was shortened by it's first character.

This was the query I then commented it out to see if it was correct.

$query = "INSERT INTO Locations (Zip, LAT, LNG, Name, Address) VALUES (01915, 45.5, 55.6, 'Name', 'Address');";


The output is


1915<br />45.5<br />55.6<br />Name<br />Address<br />


<?php
include_once('db_conn.php');
//$query = "INSERT INTO Locations (Zip, LAT, LNG, Name, Address) VALUES (01915, 45.5, 55.6, 'Name', 'Address');";
$query = "SELECT * FROM Locations";
// Perform Query
$result = mysql_query($query);
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(), etc.
while ($row = mysql_fetch_assoc($result)) {
echo $row['Zip'] . "<br />";
echo $row['LAT'] . "<br />";
echo $row['LNG'] . "<br />";
echo $row['Name'] . "<br />";
echo $row['Address'] . "<br />";
}

// Free the resources associated with the result set
// This is done automatically at the end of the script
mysql_free_result($result);
?>

traq
02-19-2011, 09:15 PM
is that first field "INT" type? since it's being treated as a number (not as a string of individual digits), leading zeros will be dropped. switch the field to VARCHAR and you should be fine (just remember to 'quote' the values when you insert them).

bluewalrus
02-20-2011, 01:17 AM
I didn't know about the leading zeros being removed thanks. Would float stop that as well or is varchar the only way?

traq
02-20-2011, 04:04 AM
Haven't tried, but I don't think FLOAT will prevent it, as mysql is still considering the value "numeric." If you think about it, a zip code is really a string, even though it's comprised solely of digits.

in php its even further from what you might expect:
<?php
//try this
$zip = 01915;
print $zip;
print "<br>";
//compared to this
$zip_str = '01915';
print $zip_str;
?>
the leading zero leads php to evaluate $zip as a numeric value written in octal notation.

bluewalrus
03-16-2011, 04:59 AM
Thanks, didn't know that I've switched it to varchar and it's working.

traq
03-16-2011, 03:52 PM
no prob