phpmyadmin convert all empty fields to NULL - php

is it possible to convert all empty fields in a database table to NULL.
one: without using a script to do it. meaning within myphpadmin?
if thats not possible
two: what would a script in php look like?
Thank you.
EDIT, this is after a database has already been created, with over 3000 rows.

UPDATE my_table
SET my_column = NULL
WHERE my_column = '';

Related

MYSQL is running but rowCount returns 0 [duplicate]

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.

how to set success message for successful mysql update and for error [duplicate]

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.

Parsing first line of csv and creating a table inside database

I am downloading new csv's each night using a cron job with PHP. Each csv is normally about the same, possibly one night within a month a field is new. I need to get the new field and append it to the database. I don't know how to get the type of the new field. I saw someone else's question with gettype() but i'm not sure if that would work or not since the data is inside a csv so wouldn't they all be strings when some need to be floats, or ints? How would I go across checking the type?
The second question, is there a way to check if there is not a name inside of a table? For instance, if they add a new field called foo52, and I have foo1 through foo51 in my database, is there a quick way to search for fields that aren't there, or would I have to use a select statement for each one and append it when it's false?
I use MySQL for my database.
Thanks for your help.
The first question on the part about getting the type is the simply try the conversion of the data itself and then seeing if the data is equivalent with a == comparison.
So,
some,data,is,123
After reading in the data you can then try the conversion to various types such as strings, ints, ect...then from that you are able to determine the type of the data.
For the second question you can get the column names by doing:
show columns from db.table_name
Then you can do a simple in_array to test if the new column name is already in the database.
EDIT:
Using array_diff can simplify the finding of the missing/new column names from the CSV.
csv_names = get_csv_column_names();
sql_names = get_sql_column_names();
new_names = array_diff( csv_names, sql_names );
I have found the parsecsv-for-php library very handy for [re|de]constructing CSV data.
For the first question: you can test if it's numeric with is_numeric(). If not, store as string. If yes, create the field as numeric in your database. If you want, you can use regex to check if it's a date or some other datatype you think is required to be stored correctly (i.e. not a a default-text)
for the second question: getting the fieldnames of a table in Postgres is done with the follwoing query
$sql = "SELECT attname FROM pg_catalog.pg_attribute
WHERE attrelid =
(SELECT c.oid FROM pg_catalog.pg_class c LEFT JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE c.relname = '$this->tableName' AND n.nspname = 'public')
AND attnum > 0
AND NOT attisdropped";
For MySQL, it should be doable with "show columns from db.table_name".
Once you have the fields, use in_array() to check if it exists already...
Note that: you'd probably need to check for all columns in your CSV if they exist already. If not: add a new colum for it. If yes, leave it as is...

Selecting NOT NULL columns from a table

My table is having approximately 80 columns. I am performing the following query on the table.
SELECT * FROM mobile_details WHERE id=4;
It is confirmed that the above query will return only one row. I want to select only the columns which are not having value NULL or empty. How can I do this?
Note: A very inefficient way to do this is to put NOT NULL in every column while SELECTing. But I need a more efficient and effective way (either in PHP code or MySQL query).
Can I do something like this? SELECT * FROM mobile_details WHERE id=4 AND mobile_details.* NOT NULL;
I am using PHP + MySQL + Apache on CentOS server.
You can't change the list of columns programmatically in SQL. There's no syntax for it.
You don't. You can do some trickery, but it's not worth it. Why not just skip the null columns when you are processing the data? It's easy enough to check for in PHP. Also, you shouldn't use SELECT * in production. Select just the columns you want and if you happen to want all of them, list them all.
You should do it in php, use function array_filter to filter the null values.

MySQL - Problem with null = 0

Im working with a mysql database via php.
I have a table with some values that are = NULL
I select these values in php:
$opponentInv = db_execute("Select * from inventoryon where playerid = ".$defendid.";");
$opponentInv = mysql_fetch_assoc($opponentInv);
Then i insert the values into a another table:
db_execute("INSERT INTO `inventoryCombat` (`attackid` ,`defendid` ,`money` ,`item1` ,`item2` ,`item3`, `item4` ,`item5` ,`item6`, `time`)VALUES ('".$attackid."', '".$defendid."', '".$opponentInv["money"]."', '".$opponentInv["item1"]."', '".$opponentInv["item2"]."', '".$opponentInv["item3"]."', '".$opponentInv["item4"]."', '".$opponentInv["item5"]."', '".$opponentInv["item6"]."', '".$time."');");
The issue is that when i insert the values into the second table, they are always coming out as 0. The values in the inventoryCombat table are 0 when they should be NULL (what they are in the inventoryon table). The table is set to accept NULL as values.
Firstly I'd strongly recommend that you use prepared statements instead of building a literal SQL string. Not only is this a better practice and helps you to write a more secure application, it also handles NULL values correctly without requiring any extra work.
If you want to continue using the method you are currently using then you will need to explicitly check for undefined values and insert the string 'NULL' into your SQL. In other words, you need to do this:
INSERT INTO inventoryCombat (item1) VALUES (NULL);
Instead of what you are currently doing:
INSERT INTO inventoryCombat (item1) VALUES ('');
If it still doesn't work, double-check that the field you are trying to insert NULL into is set to allow NULL values. You can use SHOW CREATE TABLE inventoryCombat to do this.
I'd also recommend normalizing your database. Having columns called item1, item2, item3 etc. is a sign of a bad design. Your current design will, for example, make it more complicated to perform what should be simple queries such as 'How many players possess item X?' or 'Add item X to player P unless she is already holding 6 items'.
Values in array $opponentInv is may be set to 0.
Like $opponentInv["money"] = 0; that is why it is being saved as 0 in inventoryCombat table.
Try to set value of $opponentInv["money"] as NULL in your coding, instead if 0 or ''.
e.g
$opponentInv["money"] = ($opponentInv["money"] == 0 || $opponentInv["money"] == '')?NULL:$opponentInv["money"];
This seems to be that you're storing string(varchar, text) data into number field whose default value is set to 0.
There are 2 more solutions:- Even if it has accepted the values as 0 instead of NULL, this can be updated as NULL like this:- update set =NULL WHERE ;
Also you need to check if the column is set to be NULLABLE, then only above SQL will work, else it will again set the column with 0 value and will be of no use.
Further you can do the same via your SQL Manager interface. I am not sure about all but EMS postgresql manager works this with command CTRL+SHIFT+0 and few others like sql navicat for mysql and oracle use CTRL+0 [Please check your sql manager programs on your own]. Cheers!

Categories