Execute query on enter php page - javascript

I need a query to execute when entering a page (php). I've already added this to the top.
Code:-
mysql_query("INSERT INTO `table_name` (`player_id`, `unit1`, `unit2`, `unit3`, `unit4`)
VALUES ('".$_SESSION['user']['id']."', 0, 0, 0, 0)");
When my users enter the page that contains that, the query should be executed. Yes database connection is included.
How do I fix this? (also will it duplicate player_id)?

First mysql is deprecated use mysqli.
Your query is fine how i can see, but your table could be a problem.
You should not have primary key on player_id if you wish to duplicate player_id. (Otherwise keep the primary key).
Also if you wish to have one player_id with those results (not multiple / duplicates), then you could create query in this way:
$query = "INSERT INTO `table_name` (`player_id`, `unit1`, `unit2`, `unit3`, `unit4`)
VALUES ('".$_SESSION['user']['id']."', 0, 0, 0, 0)
ON DUPLICATE KEY UPDATE `unit1`=0, `unit2`=0, `unit3`=0, `unit4`=0";
UPDATE:
Also there could be a problem that you are missing a database identifier at mysql_query:
mixed mysql_query ( string $query [, resource $link_identifier = NULL ] )
like mysql_query("MYQUERY", $mylinkISavedAtConnectingToDatabase);

Related

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.

error using json_encode on a string returned from a mySQL query

I am trying to pass an array which is the result of a mySQL PDO query from php to javascript using json_encode.
However if one of the fields contains spaces, or, if I try to use a database function on the string (to select only the first non-space part), the object seems to be nonexistent, and my code does not compile.
Following is the executed code:
<?php
$sql = "SELECT id, substring_index(firstNames, ' ', 1) as firstName, lastName, gender, idPersonFather, idPersonMother
FROM a_person";
$result = $db->query($sql);
while ($row = $result->fetch(PDO::FETCH_ASSOC)){
$personArray[$row['id']] = Array( 'firstName' => $row['firstName']
, 'lastName' => $row['lastName']
, 'gender' => $row['gender']
, 'idFather' => $row['idPersonFather']
, 'idMother' => $row['idPersonMother']);
}
?>
<html>
...
<script type="text/javascript" src="js/includes/grid_classes.js">
var personArray=<?php echo json_encode($personArray); ?>//get php aray
var someNextStuff
...etc
This will result in the error
Uncaught SyntaxError: Unexpected token var
because the line var someNextStuff comes unexpected, apparently the object is translated into an empty string?
Also, the following select causes the same problem:
$sql = "SELECT id, firstNames, lastName, gender, idPersonFather, idPersonMother
FROM a_person";
with firstNames containing values like 'Maria Anna Cecilia', and NULLs.
The SQL queries work on the database directly however (in phpmyadmin).
However, if I leave out the firstNames field from the select and the array, the code is working correctly.
What could be causing this?
thanks for your help..
Edit:
I now found that
SELECT id, substring_index(coalesce('Maria anna blah','?'), ' ', 1) as firstName, <rest of fields>
works, but
SELECT id, substring_index(coalesce(firstNames,'?'), ' ', 1) as firstName, <rest of fields>
does not.
So it has to be something with that field, I guess..
If you look at the output of json_last_error_msg (or just json_last_error if you are using an old PHP version, in which case you will only get an integer that you need to match to a constant), you will get one of these errors:
Control character error, possibly incorrectly encoded
or
Malformed UTF-8 characters, possibly incorrectly encoded
The two weird characters you found (Ã and unprintable) are what happens when you try to store UTF-8 data in a database that is not using UTF-8 encoding.
You can try to work around this by calling utf8_decode on each piece of data that might have unicode characters.
However, the best way to fix it is to make sure that your database is using UTF-8.
OK, I seems that it was indeed a false value in one of the rows in that field! (thanks Jakumi)
Patiently added more rows to the array from an ordered select until it failed, and that happens when adding the record with firstnames Ãline.
Copy Pasting I just found out that there is an unreadable character after The Ã...0089 whatever that is...
HEX c289
However just removing the value after the à character was not enough, it seems that my character set is maybe too limited. However I suspect this is dirty data, so it will go back to the source instead of me expanding the character set..

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.

Passing Mysql data to PHP array then to javascript

Let me start by explaining the situation:
I have a MySql table that contains several columns, of which a user id, a race id, a lap time, a lap number and I want to put this information into an array in PHP which I will then send to a java script.
My JavaScript array should end up looking like this :
first row:
[laptime1 user1, laptime2 user1, laptime3 user1,...]
second row:
[laptime1 user2, laptime2 user2, laptime3 user2,...]
Here's my current situation:
I first tried to test this situation for a single user and ran into lots of problems because my lap times in MySql are floats and when using json_encode it turned everything into strings, which did not work for my javascript as it started outputting the wrong values.
For example:
The first value was "8" instead of "84,521", then the second value was "4", etc..)...
Sadly, I found a potential solution with the numeric check option, but cannot use it as my hosting runs a PHP version that doesn't support it.
So I found the following solution, which I fiddled with a bit and that works for a single user (it might look messy to you, I'm really a beginner and punching above my weight, but it works) :
$query = doquery("SELECT racelaptime,userid FROM {{table}} WHERE raceid='1' ORDER BY racelap", "liverace");
while(($result = mysql_fetch_array($query))) {
$data[] = (float)$result['racelaptime'];
}
$script = $script . "\nvar myArray = new Array(";
foreach ($data as $key => $value){
if ($key < (count($data)-1)){
$script = $script . $value . ',';
}
else {
$script = $script . $value . ");\n";
}
}
This outputs an array in JavaScript that looks like this :
myArray=[84.521,83.800,81.900]
Which is great, as this is exactly what my java script requires as input (time in seconds, separated by commas for each lap).
Now I would like to implement the multiple user element but I'm stumped as to how I can work that out...
My MySQL query is still sorted by race lap but I also kind of need to sort the data by user id as I want all the laps of each user sorted in 1 row, Also, the user id is unknown to me and can vary (depends which user posts the time) so I can't really do a "if userid==1 save this here and then go to next one".
Should I use a foreach statement in the while loop that stores the data, but how can I tell him to store all the laps by the same user in the first row (and the next user in the second row, etc...) without using tons of SQL queries ?
If you can offer a more elegant solution than my current one for passing the PHP array to JavaScript, I would be more than happy to make changes but otherwise a simple solution using the current "setup" would be great too (hope it's all clear enough).
Any help would be very much appreciated, thanks in advance !
For multiple user element I would use a multidimensional array >
$query = doquery("SELECT racelaptime,userid FROM {{table}} WHERE raceid='1' ORDER BY racelap", "liverace");
// Loop the DB result
while(($result = mysql_fetch_array($query))) {
// Check if this ID is already in the data array
if(!array_key_exists($result['userid'], $data)){
// Create array for current user
$data[$result['userid']] = array();
}
// Add the current race time to the array (do not need to use the float)
$data[$result['userid']][] = $result['racelaptime'];
}
// Echo json data
echo json_encode($data);
Now what you need to do on the Javascript side when handling this array is to go through each of the user
$.each(data, function(key, value){
// Use parseFloat to keep the decimal value
alert(key + ' Has the following values - ' + value);
// If you want to display the racing values you simply
$.each(value, function(k, parseFloat(v)){
alert(v);
})
})
Is this what you needed or am I completely out of the scope?

Categories