This may sound a little stupid but I need some help.I should save some records in the database as follow by accessing the following link:
http://localhost/whatsapp/index.php?r=users/create&mobile=012345678900
This is what I have in the controller:
public function actionCreate()
{
$model=new Users;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
echo "hello"." hii";
if(!isset($_POST['number']))
{
echo "aho";
$model->number="012345678900";
//$model->number=$_POST['number'];
echo 'bye';
//$model->attributes=$_POST['Users'];
if($model->save())
echo "done";
return "Doneeee";
}
}
The data is saved correctly except the column number.Always a certain number is saved as follows:
2147483647
Any dea why this is happening?!
Sql engine generate this kind of number when data type is not bigint and length of col is less than the length of number you entered.
In your Users table change the type of number to varchar and set its length to 15 or 20 or whatever you want.
Try this query
ALTER TABLE `users` CHANGE `number` `number` VARCHAR( 15 )
Note:- You are getting this problem because you have set your number field as int type. and the biggest value int type can hold is what you are getting in the database. So changing it to the varchar type will solve the problem.
A number starting with 0 is regarding as the OCTAL representation of the number
http://en.wikipedia.org/wiki/Octal
What is happening here is that the octal number, when represented as a "normal" or "decimal" number, gets to large, and overflows in the space provided (kind of like the mileage counter in a motor vehicle). Therefore, when the number gets saved, it gets converted into a number, then overflows.
The correct treatment is to regard this as a string, as suggested by #Let me see
Related
I actually get very mad about PHP and SQLite3 and the way some of my strings behave there.
I try to save opening hours but in strings instead of numeric to prevent problem with leading zeros (and still have it now haha... -.-).
Hours and minutes have their own column but when I insert '0x' the zero is gone and whatever x is, is left in the database. :/
Im sure im just missing some little damn part somewhere...
I already checked the INSERT-statement but found nothing at all.
Example for an insert string:
INSERT INTO opening INSERT INTO opening (start_day, end_day, start_hour, start_minute, end_hour, end_minute) VALUES('Montag', 'Freitag', '00', '00', '01', '00')
But the output is:
11|Montag|Freitag|0|0|1|0
Part of the Code:
class Database_Opening_Hours extends SQLite3{
function __construct() {
if(!file_exists("../../data/opening_hours/opening_hours.sqlite")){
$this->open("../../data/opening_hours/opening_hours.sqlite");
$this->exec('CREATE TABLE opening (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, start_day STRING, end_day STRING, start_hour STRING, start_minute STRING, end_hour STRING, end_minute STRING)');
}
else{
$this->open("../../data/opening_hours/opening_hours.sqlite");
}
}
}
$db = new Database_Opening_Hours();
$insert = "INSERT INTO opening (start_day, end_day, start_hour, start_minute, end_hour, end_minute) VALUES('".htmlspecialchars($_GET["start_day"])."','".htmlspecialchars($_GET["end_day"])."','".$start_hour."','".$start_minute."','".$end_hour."','".$end_minute."')";
if($db->exec($insert)){
$db->close();
unset($db);
echo "Insert erfolgreich";
}else{
$db->close();
unset($db);
echo "Nicht wirklich...";
}
Fairly sure that the type of your columns is set to an integer (or any other number type) instead of TEXT.
Make sure to double check the column data type and actually dump the table for us to check if it's really set to TEXT.
This is caused by SQLite using dynamic typing. From the FAQ:
This is a feature, not a bug. SQLite uses dynamic typing. It does not enforce data type constraints. Data of any type can (usually) be inserted into any column. You can put arbitrary length strings into integer columns, floating point numbers in boolean columns, or dates in character columns. The datatype you assign to a column in the CREATE TABLE command does not restrict what data can be put into that column. Every column is able to hold an arbitrary length string.
And from the linked page (emphasis mine):
In order to maximize compatibility between SQLite and other database engines, SQLite supports the concept of "type affinity" on columns. The type affinity of a column is the recommended type for data stored in that column. The important idea here is that the type is recommended, not required. Any column can still store any type of data. It is just that some columns, given the choice, will prefer to use one storage class over another. The preferred storage class for a column is called its "affinity".
So SQLite is dynamically casting your values to integer.
I would suggest combining start_hour and start_minute into start_time (the same for the end_ fields) and storing the value in the format 00:00.
SQLite will store this 'as-is' but is smart enough to recognise a time value and allow you to perform date/time operations:
select time(start_time, '+1 hour') from opening
I had this problem with C/C++ because I did not quote the strings:
insert into test values('aa', 'bb');
use varchar instead of string, I had the same problem then I used varchar(length) and it worked fine
I am trying to build a simple web app to keep up with my debt and I want to use the same database table for adding and also subtracting data.
I am converting the input from the input field using a simple php operation to convert it to a negative number:
$sum2 = $sum*-1;
$sum being the input field:
$sum = $_POST['shuma'];
The Idea is, when I input a positive number, my debt grows larger, when I input a negative number, my debt gets smaller, it's a simple idea.
In MySQL database, I am inserting the input into:
decimal(7,2) Default:Null
The problem is, the positive input, even though it's being converted into a negative number, it's not being inserted as negative in MySQL, it inserts it again with a positive number. The problem it's not within PHP because I tested it and even after the form it's submitted and data it's pushed into MySQL, I still can get the negative number shown using the echo in PHP.
Does anyone have any idea how to solve this?
P.S. Maybe I should mention, when I try to insert negative directly from phpmyadmin it works, it accepts the negative number in the same field.
Thank you.
change you field type to DECIMAL (10,2) . Field length defination is on you. Define length according to your requirement.
In this case negative value will be inserted. If not, then please die(); your query and execute it directly in mysql. Because for another field's problem also negative value not insert in table though the field type is DECIMAL.
Well, I am trying to use the same input field for both, only use a
checkbox, when the box it's checked, it's a negative number, otherwise
it's positive
About that comment.
i.e. you have
<input type="checkbox" name="negative"/>
<input type="text" name="sum" />
<?php
$sum = (int)$_POST['sum'];
...
so you can have, let's say two methods:
function increase($value) {
return query("UPDATE table SET value = value + $value");
}
and
function decrease($value) {
return query("UPDATE table SET value = value - $value");
}
so you are checking:
if(isset($_POST['negative']) {
decrease($sum);
}
else {
increase($sum);
}
However, the queries are just a sample, I just wanted to explain the logic, where you don't need to add the number with negative sign, but you can change the query depends on the checked inputs
How can I automatically generate a unique, random 6 digit number to insert into a column of a mysql table? The randomly generated number must not already exist in the column.
I am accessing mysql via php.
The table format is like so, with the random number going in the reqnumber column:
id,status,reqnumber
function gen(){
$num = rand(100000,999999);
if($num == ifnumberinyourdatabase){
gen();
}
return $num;
}
You can also use recursive function here.
which check's if number is your database if it is generate new one if not return the unique number
function gen(){
$num = rand(100000,999999);
$query_idgetrs = "SELECT * FROM servicetbl where reqnumber = $num";
$idgetrs = mysql_query($query_idgetrs, $dbconnection) or die(mysql_error());
$row = mysql_num_rows($idgetrs);
if($row >= 1){
gen();
}
return $num;
}
Just generate a random number and then use str_pad():
$myRandom = str_pad(rand(1,999999), 6, '0', STR_PAD_LEFT);
The problem that you're going to run into is that since you require this to be random, there's no way to know if it exists in the table until it's generated. You'd have to make a loop and keep checking in DB.
Put unique constraint on reqnumber field and put error handling code in PHP
Although random is ok, please note that 6 digits only offers 1 million combinations. I'm not sure how long it would be before you started getting duplicate primary key errors.
A much better solution would be to use a unique value. This is very different to a random value as the unique value guarantees to by different every time. MySql has the auto_increment datatype to help you with this. Unfortunately, you are still limited to 1 million entries when using 6 digits.
If you want a totally random, long identifier, check out MySql's UUID function. It will generate a unique string that is guaranteed to never repeat. However it is much longer than 6 characters because that's what it can take to achieve uniqueness.
A part of your table structure must be:
`id` mediumint(6) AUTO_INCREMENT NOT NULL,
PRIMARY KEY (`id`)
If you really need 6 digits always:
ALTER TABLE tbl AUTO_INCREMENT = 100000;
or use
sprintf()
If the mobile number 1234567890, the below code is working fine.
If the mobile number is either 2134567890 or another other number not starting with 1, the below code is inserting this number "2147483647" and code is not giving correct output.
Using POST method of FORM i'm getting the values and ACTION is $_SERVER['PHP_SELF']
Using isset($_POST['submit']), written below the code.
Here is the Code:
$sql=mysql_query("insert into registration (regname,regmobile) values ('$_POST[regname]','$_POST[regmobile]')");
$sql1=mysql_query("select * from registration where regmobile='$_POST[regmobile]'");
if(mysql_num_rows($sql1)>0)
{
while($row=mysql_fetch_array($sql1))
{
$regname=$row['regname'];
$regmobile=$row['regmobile'];
$regid=$row['regid'];
$reguserid=substr($regname,1,2).substr($regmobile,-4).substr($regid,-2);
$sql2=mysql_query("update registration set reguserid='$reguserid' where regmobile='$regmobile'");
}
}
Thanks & Regards
Swetha
Consider a different data type:
bigint
-2^63 (-9,223,372,036,854,775,808) to 2^63-1 (9,223,372,036,854,775,807)
int
-2^31 (-2,147,483,648) to 2^31-1 (2,147,483,647)
smallint
-2^15 (-32,768) to 2^15-1 (32,767)
tinyint
0 to 255
Alternatively as mentioned by blue112, try using VARCHAR
That's because you've reach the limit of Mysql Int.
Consider using a Varchar(10), it will work better.
This is because you have reached the limit of int
you should use BIGINT.
Something like this
i am using $_GET['var'] to get a variable then compare it with a variable in my database. the variable is 1.1 the var is set to "float" on the database so i know it can handle decimals but when i compare them with the code below i get nothing.
include 'connect.php';
$sql=mysql_query("SELECT * FROM table WHERE stuff='$stuff'");
while ($row=mysql_fetch_assoc($sql)) {
$start=$row['start'];
}
echo $start; //nothing happens
From what I know float type isn't precise. It doesn't show you that actual value so 1.1 that you saved may not be the actual value stored. Trying setting your field as decimal and give it a length of say, 10,1 where 10 is the maximum number of digits (the precision) and 1 is the number of digits to the right of the decimal point (the scale). It should work doing query like stuff='1.1' or stuff=1.1.
WHERE stuff = '$stuff' is a String comparison.
Compare number like so
WHERE stuff = $stuff
Don't use float( even if you insert 1.1 into the table, the actual value for float type is not 1.1, but something like 1.100000023841858) . Change it to double in database (or decimal)
You might not be seeing any output because your echo is outside the loop.
The scope of your variable $start would be confined to the loop.
Change the stuff field to DOUBLE type.
Then,
SELECT * FROM table WHERE stuff=$stuff
this should be the sql query