I am trying to add the value "006" to an MySql row, but it shows up as "6"! any fixes on my code ?
$id = "006";
mysql_query("INSERT INTO Table (id) VALUES ($id) ");
Thanks,
If id is a numeric column such as an integer, 006 is the same as 6 so there isn't a way to explicitly save 006 since its exactly the same as 6.
But if you want to retrieve that integer as a 3-digit, zero-padded string, you could use the LPAD function to pad it with 0's on the left side:
SELECT LPAD(id, 3, '0') as id FROM table;
Although this is not a safe way:
$id = "006";
mysql_query("INSERT INTO Table (id) VALUES ('$id') ");
I think you forgot some quotes on values, so its cast to int.
Your field needs to be a VARCHAR for that to work as you desire. You may also pad leading zeroes when you run your queries as an alternative.
I suppose that's just incorrect value (for the int field type) and cannot be stored at all.
Database intended to store data, means data without any additional formatting, which can be added at select time. That's how this thing works in general.
So, I'd suggest to store a regular int, and pad it with whatever number of zeros you wish at select time
Try to use query in mysql.
ALTER TABLE table MODIFY COLUMN id INT(3) ZEROFILL;
this may solve your question.
Related
I have this query:
UPDATE phonecalls
SET Called = "Yes"
WHERE PhoneNumber = "999 29-4655"
My table is phonecalls, I have a column named PhoneNumber. All I want to update is a column named Called to "yes".
Any idea what I am doing wrong? when I return my query it says 0 rows affected.
If the such value already exists, mysql won't change it and will therefore return "0 rows affected". So be sure to also check the current value of called
Another reason for 0 affected rows that I have observed: wrong data type. If the column you want to update is an integer or boolean, and you set it to a string, it won't be updated - but you will also get no error.
To sum up the other strategies/ideas from this post:
Check with a SELECT statement, whether your WHERE works and returns results.
Check whether your columns do already have the value you want to set.
Check if your desired value suits the data type of the column.
If the values are the same, MySQL will not update the row (without triggering any warning or error), so the affected row count will be 0.
The problem might be that there are no records with PhoneNumber == "999 29-4655".
Try this query:
SELECT * FROM phonecalls where PhoneNumber = '999 29-4655'
If it doesn't return anything, then there are no rows that match.
For the benefit of anyone here from Google, this problem was caused by me because I was trying to append to an empty field using CONCAT().
UPDATE example SET data=CONCAT(data, 'more');
If data is NULL, then CONCAT() returns NULL (ignoring the second parameter), so the value does not change (updating a NULL value to be a NULL value), hence the 0 rows updated.
In this case changing to the CONCAT_WS() function instead fixed the problem.
Try select count(*) from phonecalls where PhoneNumber = "999 29-4655"; That will give you the number of matching rows. If the result is 0, then there isn't a row in the database that matches.-
Check to make sure this returns some result.
SELECT * FROM phonecalls WHERE PhoneNumber = '999 29-4655'
If it doesn't return any result than the filter WHERE PhoneNumber = '999 29-4655' is not correct.
Does it say Rows matched: 1 Changed: 0 Warnings: 0? Then maybe it's already set to that value.
Did you try single quotes vs. double quotes?
"999 29-4655" is the space a space or a tab and is it consistent in your query and the database?
That's my sugestion:
UPDATE `phonecalls` SET `Called` = 'yeah!' WHERE `PhoneNumber` = '999 29-4655' AND `Called` != 'yeah!'
And make sure with the case-sensitive name of table and field`s.
Just ran into an obscure case of this. Our code reads a list of records from the database, changes a column, and writes them back one by one. The UPDATE's WHERE clause contains only two conditions: WHERE key=? AND last_update_dt=?. (The timestamp check is for optimistic locking: if the record is changed by another process before we write ours, 0 rows are updated and we throw an error.)
But for one particular row the UPDATE was failing- zero rows effected.
After much hair-pulling I noticed that the timestamp for the row was 2019-03-10 02:59. In much of the U.S. that timestamp wouldn't exist- Daylight Savings Time causes the time to skip directly from 2:00 to 3:00. So I guessed that during the round trip from MySQL to Java back to MySQL, some part of the code was interpreting that timestamp differently from the rest, making the timestamps in the WHERE clause not match.
Changing the row's timestamp by one hour avoided the problem.
(Of course, the correct fix is to abolish Daylight Savings Time. I created a Jira but the U.S. Government has not responded to it yet.)
In my case, I was trying to update a column of text to correct a truncation problem with it. Trying to update to the correct text was yielding 0 rows updated because the text in the row wasn't changing.
Once I extended the column in the table structure to accommodate for the correct number of characters, I was able to see the desired results.
I need to save numbers to database as it is please see the example.
currently i save number as 22.5 and in database it is saved as 22.
number in database is set as integer
//sometimes $number can be "33.5" or "33" or "1" or "1.003"or "03"
$sql = "INSERT INTO active (name, number) VALUES ('somename','$number')";
If you make your number column as DECIMAL data type, it will hold the decimal point with all numbers. Integer columns cannot hold decimal points.
If it is not your requirement, better use VARCHAR as data type (But NOT RECOMENDED).
Hope this helps.
First of all, you need to check the structure of active table. From your question, I understand that various types of number values is going to be saved to number column. And I guess the type of number column in active table is numeric for int types. For example, INT or BIGINT or any other integer types.
Here is what I'm usually doing. Just use varchar for number field. It might not sound like professional. But it's very easy to use. By doing so, you won't have any problem with saving numeric value to the column. I have got an similar issue before while saving latitude and longitude value to the table. And php has got many functions to get actual float or int value from string. So this is an easy and simple way to fix.
One of the easiest and reliable way to save the numbers/integers/floats to the database is to convert them to string and then storing them into the database.
Note : Your database column type should be of type string/text.
One of the advantage of this method is that you can overcome the limits of int/float/double.
$string_number = (string)$number;
$float_number = (float)$string_number;
If you want to save number as 22.5 and in database. Then you need to change table column structure. Instead of Integer/Int set to float Then Next set length 10,2
for information please check below screen short
Then you get proper output Happy Programming
I'm trying to count a table row and add 1 on the outcome, I have this snippet of code.
$countQuery = "SELECT COUNT(id) FROM donations";
$outcomeQuery = mysql_query($countQuery);
$countUp = mysql_fetch_array($outcomeQuery);
$plusOne = 1;
$outcome = $countUp;
echo $outcome[0]
or die(mysql_error());
But this gives me the error:
Fatal error: Unsupported operand types
I need this so I always have a unique number that's not used by a previous donator.
You could use:
SELECT COUNT(id)+1 as IDCount FROM donations
as your query instead. This will save you any mucking about in PHP to do the math. The array you pull back will have the number that you want right off the bat.
Edit: The better alternative however is to use a column type that increments automatically. In MySQL, this is done with the syntax auto_increment in the create table syntax.
Using this, you never actually have to insert a value, but rather, you pass it a NULL as follows (assuming that ID is the field with Auto_increment on it:
insert into tableName (ID,Name) values (null, 'Fluffeh');
So you see you don't give it any values for the ID column - the database takes care of using the right number.
use simple php
$countQuery = mysql_query("SELECT id FROM donations");
$count=mysql_num_rows($countQuery);
$count+=1;
It's dangerous to rely on COUNT to give you a unique number. What happens if two processes execute this query, and then both try and commit: you suddenly have the same value twice.
It would be much safer to implement some kind of sequence function independent of your table contents. This link shows one possibility:
http://forums.mysql.com/read.php?61,143867,238482#msg-238482
This question is for a MySQL database. I suggest you use the AUTO INCREMENT field type.
As you are using PHP, if you need to know the id after inserting a record, use:
mysql_query("INSERT INTO mytable (1, 2, 3, 'blah')");
$id = mysql_insert_id();
See mysql_insert_id().
Using
4 random generated numbers to make 100% sure there are no duplicates
will not make 100% sure there are no duplicates. Don't re-invent the wheel. This is how the problem of ensuring unique incrementing identifiers are used has been solved, you don't need the embarrassment of a homebrew solution that doesn't always work.
I'm trying to find the max value contained in two separate fields of my table.
The code I'm using in my model is:
$query = $this->db->query("select max($field1) as max_id_1 from default_table1");
$row1 = $query->row_array();
$query = $this->db->query("select max($field2) as max_id_2 from default_table1");
$row2 = $query->row_array();
return max($row1['max_id_1'], $row2['max_id_2']);
I'm a complete novice where PHP and CodeIgniter is concerned - as I'm sure my code demonstrates :)
It is working insofar as it's returning values, but not the maximum values I have in the fields. For instance I know there is a 4000 value but the highest returned is 750.
I'm wondering if this is because the fields are of type VARCHAR because although they predominantly contain numbers there are some that contain characters (- or &) or the word 'to' so I couldn't use the INT type.
Because of using VARCHAR is it failing to see that 4000 is larger than 750?
If so is there a way to cast the field contents as integer before checking for the max value, and will this be affected by the non-integer values in the fields?
All offers of help and advice is gratefully received.
Tony.
This can be done using SQL using MySQL's implicit type conversion:
select max(case when (field1+0)>(field2+0) then field1+0 else field2+0 end)
from default_table1
Using +0 would convert varchar to number and also ignore any characters that follow after the number. If you still need the original content, you can write the query like this:
select case when (field1+0)>(field2+0) then field1 else field2 end
from default_table1
order by case when (field1+0)>(field2+0) then field1+0 else field2+0 end desc
limit 1
Oh, oops, I've forgot the mysql part
You should do the same thing, cast to integer:
select max(cast($field1 to unsigned)) as max_id_1 from default_table1
It depends of your data, but you may try something like that
return max((int)$row1['max_id_1'], (int)$row2['max_id_2']);
Have a look to the PHP doc on string to int conversion
What you are really asking for is a way for codeigniter to convert the strings to numbers, and the find the max values of those. I don't know of any way to do this in codeigniter.
If you really want this, you have two options:
loop through all the rows in the table, and use php to parse out the number, while looking for the maximum number
Add a number column to the db, and do the string-to-number parsing in this new column whenever the values are inserted.
The first option is incredibly inefficient, and the second is probably your best bet.
I need to pull from MYSQL a value , than change forward the value and insert in to the mysql.
for example :
$str = mysql_fetch_assoc(mysql_query('SELECT `str_id` FROM `ids` ORDER BY `num_id` DESC LIMIT 1 ')); // = aaa
$str = $str++; // aaa -> aab
// than check if "aab" key already exist
// if not , insert as key as "aab"
as for this algorithm there is a risk that this script runs from the two sides of the globe and two unique keys will be sign as "aab"..
how can i do this without risk of sign this unique key two times?
If you set up your database so that the column is unique, the MySQL table will not allow you to add the same value twice. You can then check the result of the transaction to ensure that it succeeded.
From your example it looks like you just want an incremented unique key. You should use an integer for this, which can automatically increment when you insert a new row. If you want it to be in string form just perform some basic math on it. i.e.
1 = a
2 = b
...
27 = aa
28 = ab
This is assuming you don't already have a primary key on your table, in which case I don't understand why you need the string in that form. Hopefully this helps, and I apologize if I misunderstood the question.
When using MySQL-InnoDB you should use Transactions (Provided by MySQLi and PDO) for that cause. MyISAM does not support it.
Here is the manual about transactions in PDO: http://php.net/manual/en/pdo.transactions.php