How to set my empty string data to become zero in MySQL? - javascript

I wanted to ask you guys if there is an answer to my query.
My query is this, in my table I want to save an empty string "" value and save it to my MySQL table but I wanted to have it as 0 value. here is an illustration
Table -> MySQL
"" 0
thank you

In PHP, do:
if($string == "")
$string = 0;
And then use it in your MySQL query. Hope that helps!

You can make trigger ON BEFORE INSERT\UPDATE
CREATE
TRIGGER trigger_name
BEFORE INSERT
ON table_name
FOR EACH ROW
BEGIN
IF NEW.field_name = "" THEN
SET NEW.field_name = 0;
END IF;
END
Better to do it on the client side...

In your database if the column is defined with datatype 'int' then passing ''(empty string) will have mysql insert it as 0.
Example :
insert into table_name (`column_name`) values ('');

Related

how can i store auto increment id with string in postgress sequelize

I want to store the document id in the form of (IP-01, IP-02, IP-03) in the sequelize table. I tried to use autoincrement function on a string, but it showed an error that it can work only on INTEGER value.
I want to store it in such a form that I can store and search easily in the form of (IP-0X). So please anyone can help me
So I will give you basic idea, implementation is on you. There is no default function available using which you can autoincrement the value of string. My solution might not be the optimal way to do it but I guess it will solve your problem.
There are 2 option, you can implement some logic to achieve our required output.
On application level :-
By using count utility of sequelize you can count the total no of columns and generate your desired string.
//wherever you are creating the document add following
const count = (await Document.count()) + 1;
const newId = 'IP-' + count;
await Document.create({
id: newId,
...
});
On Database level:-
You need to create a function which will return the id string in required pattern.
CREATE OR REPLACE FUNCTION get_id()
RETURNS varchar
LANGUAGE plpgsql
AS $$
BEGIN
RETURN (SELECT 'IP-' || (SELECT count(1) from table_name) + 1);
END;
$$;
Now you just need to set default value of your id field to function call.
Before doing below changes you need to make sure that you have created get_id function in you database or else you will get function not defined error from database.
\\add this to file where you define your model
id: {
type: Sequelize.STRING,
defaultValue: Sequelize.fn('get_id')
}
Here is a demo of database level solution. LINK
EDIT
You can use one more approach instead of counting number of columns you can maintain a Sequence in your database and get the next Integer value from that.
CREATE SEQUENCE document_id_seq
INCREMENT 1
MINVALUE 1
MAXVALUE 9223372036854775807
START 1;
-- Then create your get_id function as below:
CREATE OR REPLACE FUNCTION get_id()
RETURNS varchar
LANGUAGE plpgsql
AS $$
BEGIN
RETURN (SELECT 'IP-' || nextval('document_id_seq'));
END;
$$;

increment value in database using PHP and AJAX

I am trying to make value +1 in database every time use use button.
my function in HTML:
function onClick(arg){
alert("thx fo click");
$.ajax({
type: 'POST',
url: 'data.php',
data: {
'arg': arg,
},
success: function(response) {
}
});
}
arg means value of button and it is a ID for a row in the database
and PHP:
<?php
$link = mysql_connect($servername, $username, $password);
$id = $_POST['arg'];
$sql = "UPDATE Buttons(SUMA) SET SUMA = SUMA + 1 WHERE ID = '$id'";
$conn->query($sql);
mysql_close($link);
?>
And that make nothing. How can i fix it?
You have several syntax errors here.
First and foremost though, check out mysqli_ (or PDO) and start using that instead of mysql_
For why to use mysqli_ - MySQL vs MySQLi when using PHP
Comparing mysqli_ and PDO - https://websitebeaver.com/php-pdo-vs-mysqli
With that out of the way....
You're defining your database connection without selecting a schema, but don't reference your schema in the query, meaning mysql won't know what to update. Either reference your schema in the connection or in each query. Also check on your table name, is it really Buttons(SUMA)?
You defined your database connection as $link, but are using $conn to attempt the query. Probably a 'typo' from copy and paste. Be careful of this...
As Artistic Phoenix mentioned, you have to make sure you're column cannot be set to NULL, and starts at 0 to begin. While you're at it and we're going through, make sure your datatype is set to int for the increment count.
After making those changes if you don't have success, I'd try running your query outside your code in a DB manager to ensure that portion is having the intended affect on your data, before looking at the errors in your code.
I'm guessing the arugment is passing correctly to your script, but to confirm, you can always echo it on the backend, and to be doubly sure alert() it in JS before it's passed through.
Take the time to go through that reading, update your script to use mysqli_ or PDO, and if you're still having troubles, I'm more than happy to jump back in here and help you further.
What is 1 + NULL it's still NULL.
IF you didn't default the column to '0' , then you can't increment it.
This can best be shown in a simple DB fiddle
Starting Null:
CREATE TABLE t(
id INT(10),
v INT(10)
);
INSERT INTO t (id)VALUES(1);
SELECT * FROM t;
UPDATE t SET v = v+1 WHERE id=1;
SELECT * FROM t;
In Both selects you will get a value of null for v as seen below in the fiddle:
https://www.db-fiddle.com/f/m1vgKpov1oiRJEfZEgmk1j/0
In simple terms, you cannot add 1 (or any number) to a NULL value. Well you can but it's still null. null + 1 = null
Starting 0:
CREATE TABLE t(
id INT(10),
v INT(10) default 0
);
INSERT INTO t (id)VALUES(1);
SELECT * FROM t;
UPDATE t SET v = v+1 WHERE id=1;
SELECT * FROM t;
In this case the first Select return 0 for v and the second returns 1 for v. As seen in the modified fiddle.
https://www.db-fiddle.com/f/m1vgKpov1oiRJEfZEgmk1j/1
Also (SQLInjection)
As I said in the comments:
What if arg = "' OR 1 --"
Or in other words don't inject user variables (or any clientside data) into your SQL or it winds up looking like this:
UPDATE `Buttons(SUMA)` SET SUMA = SUMA + 1 WHERE ID = '' OR 1 --'"
Which will increment every row in your DB that is not null. Basically the ' closes the other quote, then OR 1 is always true(for every row). Unfortinalty I cant show the -- comment part in the fiddle (it comments out the second select), but here is the end result.
https://www.db-fiddle.com/f/m1vgKpov1oiRJEfZEgmk1j/3
This is why we use prepared statements. This example is somewhat trivial but I have seen login code on here I was able to bypass simple by putting "' OR 1 LIMIT 1 --'" in, and with offset you could iterate though each user. They were looking for 1 row to be returned on the match of a username and password.
A few other things:
Table name Buttons(SUMA) is that really the name, as it will only work if escaped with the backtic. As I did in the above SQLInjection example.
$link = mysql_connect($servername, $username, $password); are these defined, the open tag is right above them. I generally chock that up to simplified example code. But it's worth asking. Obviously you can't connect to the DB if those are undefined.
Cheers!

Inserting or Updating multiple values into a MySQL table using Node.js

I have a table that has a composite primary key of (room_id, x_coord, and y_coord) and another column called card_id. I am trying to insert several records into a mysql database. I am using the mysql library as well as the express library for node.js.
If the record does not exist I would like to insert a new record consisting of room_id, x_coord, y_coord, and card_id.
On the other hand, if the record does exist, I would like to update the current record to the new card_id.
Here is a copy of my current code:
//previously defined: room_id, x, y, and cards[]
var i = 0;
var db_values = [];
for (var row = 0; row < y; row++){
for (var col = 0; col < x; col++){
card = cards[i];
//The following line may have a problem?
db_values.push([room_id, col, row, card['id'], card['id']]);
i++;
}
}
sql = "insert into user_card(room_id, x_coord, y_coord, card_id) values ? on duplicate key update card_id = values(?)";
//The following line may have a problem?
db_connection.query(sql, [db_values], function (err, result){
if (err){
console.log("Upsert DB ERROR: " + err);
return;
}
});
I have tried various combinations of code each yielding different errors. The one above yields the following error:
ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual
that corresponds to your MySQL server version for the right syntax to
use near '?)' at line 1
What am I doing wrong here and what can I do to solve this problem?
First, I believe the number of question marks in your prepared statement should match the length of your argument list (db_values Array).
Second, you don't want parentheses around the value in your update clause. Ref https://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html
Maybe a statement more like this would work:
insert into user_card(room_id, x_coord, y_coord, card_id)
values (?, ?, ?, ?)
on duplicate key update card_id=?
EDIT:
That query would only work for a single card. You probably want to create an insert statement for each card, which requires that you build the query inside of a loop. Also, it looks like db_values would be an Array of Arrays and you're passing it to the db_connection.query method with another Array. I imagine that method probably only wants a single Array of Strings.
To solve this problem you have to change the last ? to the column name that you want inserted.
So change this line:
sql = "insert into user_card(room_id, x_coord, y_coord, card_id)
values ? on duplicate key update card_id = values(?)";
To this line:
sql = "insert into user_card(room_id, x_coord, y_coord, card_id)
values ? on duplicate key update card_id = values(card_id)";
It is also important to make sure that you surround [db_values] with brackets in your query in the following line:
db_connection.query(sql, [db_values], function (err, result){
That was one area that was also giving me trouble as I was originally trying it without the brackets.

Cannot delete from mysql (file.size)

First I inserted a new record into a database with a field file_size. It all works fine. Then I want to delete the record with a given name and size from the database. It works with name, but when I add AND statement it doesnt work.
$conn->query("DELETE FROM mytable WHERE name LIKE '%{$t}' AND file_size = '$file_size'");
file_size is passed through $file_size= $_POST['size']; and it works correctly. The number in the database and the one passed is the same. I have no idea why the above doesnt work...at first I thought that maybe these are different data types and hence I am comparing string with integer, but in Javascript it shouldnt matter...Any advice would be greately appreciated.
Maybe prepare request
$query=$conn->prepare("DELETE FROM mytable WHERE name LIKE :like_param AND file_size = :filesize");
$query->excute(array(':like_param' => '%'.$t, ':filesize' => $file_size));

Check MySQL if data already exists, if not, INSERT. [PHP+jQuery Ajax]

I'm having trouble creating php code that would insert values into MySQL database but only if they don't already exist.
I send array from javascript to PHP file using $.ajax type POST.
Do I need additional 'SELECT' query to check if values already exist?
PHP File(Works, inserts values):
<?php
SESSION_START();
include('config.php');
if(isset($_POST['predictedMatches'])&&$_SESSION['userid']){
$predictedMatches=$_POST['predictedMatches'];
$userid=$_SESSION['userid'];
}else die("ERROR");
$sql="";
foreach($predictedMatches as $predictedMatch){
$sql.="INSERT INTO predictions(result,userFK,matchFK,tournamentFK) VALUES('".$predictedMatch['result']."','".$userid."','".$predictedMatch['id']."','".$predictedMatch['tourid']."');";
}
if($conn->multi_query($sql) === TRUE){
echo "OK";
}else{
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Use the ON DUPLICATE KEY UPDATE feature. It won't insert, if the primary key exists. But you have to update some value, so use the column which is in no index or in the least indexes () in your case probably result). Your primary key has to be composted out of the three FKs:
ALTER TABLE `predictions` ADD PRIMARY KEY( `userFK`, `matchFK`, `tournamentFK`);
PHP-Code, just the SQL statment (I'm a Java Guy, so i tried my best)
$sql.="INSERT INTO predictions (result, userFK, matchFK, tournamentFK) "
."VALUES('".$predictedMatch['result'] ."','".$userid."','"
.$predictedMatch['id']."','".$predictedMatch['tourid']."') "
."ON DUPLICATE KEY UPDATE result = result ;";
To know if the query was inserted you have to look at the affected row count:
1 Row - Insert
2 Rows - Update
Take a look at $conn->affected_rows after the query.
Performance
INSERT ... ON DUPLICATE KEY UPDATE is definitively faster than a SELECT and INSERT but it's slower than an INSERT of just the needed datasets. The update is done in the database, even if it is the same value. Unfortunately there is no ON DUPLICATE KEY UPDATE INGNORE. If you have a lot of inserts, that will result in updates, than it may be better to use a cache, lookup values in an array and compare with the array before inserting. Only use the ON DUPLICATE KEY UPDATE as fallback.

Categories