MySQL - Problem with null = 0 - php

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!

Related

Deleting a row which is based on a varchar primary key in php

I'm trying to delete a particular row in a table in php and I'm trying to use the primary key which happens to be of the type varchar, the primary key is course_Code
course_Code||course_Title||credit_Load||lecturer_id
csc 450 || S.E || 3 || 0
lecturer_id will always be 0 for all records added because I want to use it as a foreign key, only then would the value be changed from 0 to something else; the problem is when I have only one value in the table and I delete it, the query runs but a new row gets added with only credit_Load and lecturer_id having values of 0 while the other columns remain empty:
course_Code||course_Title||credit_Load||lecturer_id
|| || 0 || 0
This is the code i've written for firstpage.php, the value in $result['course_Code'] is the course code fetched from the database:
<a href="processor3.php?coursecode=<?php echo $result['course_Code']; ?>
Then processor3.php:
if (isset($_GET['coursecode'])){
$course_id = $_GET['coursecode'];
$query = mysql_query("DELETE FROM courses WHERE course_Code = '$course_id'");
header("Location:firstpage.php?succ=2");
}
I know I'm using the deprecated way of connecting to mysql in php, but that's not the main issue, I'm trying to teach someone php and he didn't seem to understand pdo bindings very well, so I want us to progress slowly to pdo. I guess I'm a bad teacher.
Terrible, terrible TERRIBLE!!!
$query = mysql_query("DELETE FROM courses WHERE course_Code = '$course_id'");
Please never teach anybody to query this way. ALL variables should be escaped, as otherwise there is SQL INJECTION vulnerability.
As for your problem, I suspect 2 possible issues:
somewhere without your knowledge a script to add row is called
you are using wrong MySQL viewer to confirm contents of the table after deletion.
Are you sure neither of the above is happening?

Questions Regarding Transactions (or table lock?) in MySQL/PHP

I have a question that seems pretty basic but am having trouble finding the most efficient solution.
Suppose I have this table, table KEYS
KEYS
KEY_ID VALUE USED
1 123ASD 1
2 ASD234 0
3 123456 0
I want to have an API (Going call it get_key.php here) that will access the db for the last value with used=0, return the key in JSON format to be interpreted to the user via ajax, and then mark the key as used in the db.
I've seen thoughts about lock table, but my worry is that there is a script constantly generating and inserting keys into the DB while tons of users will be requesting keys.
What is the best way to achieve this while still being safe against duplicate entries being sent out, table locks causing long delays in web page delivery, and still being able to insert while retreiving?
If you are still confused, here is a basic example...
get_key.php
//not real file just pseudo
//(lock table?)
//SELECT VALUE, KEY_ID FROM `KEYS` WHERE USED = 0 LIMIT 1;
//$key = $response['VALUE']
//echo out key in json format
//$key_id = $response['KEY_ID']
//UPDATE `KEYS` SET USED = 0 WHERE KEY_ID = $key_id;
//(unlock table?)
insert_key.php
//$key = $_GET['value']
//(lock tables?)
//INSERT INTO `KEYS` (VALUE) VALUES ($key)
//(unlock tables?)
I know this setup in production setting would be extremely insecure, but trying to make as simple as possible so you can understand my question properly.
Thanks so much for your time!
Use InnoDB or any other engine which supports row-level locks. Then you only ever have to lock the one row in question that you're selecting/updating, e.g.
SELECT VALUE, KEY_ID
FROM `KEYS`
FOR UPDATE // <--- add this row
WHERE USED = 0 LIMIT 1;
... do other stuff
UPDATE `KEYS`
SET USED = 1
WHERE KEY_ID = xxx;
COMMIT;
MySQL will lock the record it finds, and then only this particular DB connection will be able to modify that record until it's unlocked or the connection is closed.

phpmyadmin convert all empty fields to NULL

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 = '';

Count SQL table row and add 1 on the outcome

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.

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.

Categories