Multiply an insert in database from php - php

I have a php that inserts a number to my database. I would like that every value of 1 should be 0,01 in the database so if a person enters 50 it will be inserted as 0,5 in the database. This means i have to multiply the number from the php with 0,01. Is this possible? I have this code which insert the number to the database $sql = "insert into $DB_Table (score) values('$points');";

First of all you should probably look into mysqli, which will grant you safer interaction with mysql.
You could solve your problem like this though:
$sql = sprintf("INSERT INTO %s (score) VALUES ('%s');", $DB_Table, $points * 0,01);
In mysqli the corresponding would be something like:
$stmt = $db->prepare("INSERT INTO $DB_Table (score) VALUES (?);");
$stmt->bind_param("s", $point * 0,01);
$stmt->execute();
This helps you avoid SQL injection and the such.
Good luck with your project.

$sql = "INSERT INTO $DB_Table (`score`) VALUES('" . ($points*0.01) ."');";

have you tried
$sql = "insert into $DB_Table (score) values('".($points / 100)."');";
Also you don't mention what datatype your field is; I believe decimal is what you need, not int

$sql = "insert into $DB_Table (score) values('" . ($points / 100) . "');"

Related

Can't get mysql_insert_id() method to grab value I need

I'm trying to grab SID from the insert into the first table (stories) so I can insert that SID into the writing table in my second insert.
I think the way to do this is with mysql_insert_id(); after the first query, but the primary key that auto-increments is called SID. If mysql_insert_id() could grab that value I'd be all set.
What I am finding from a var_dump is that the $SID = mysql_insert_id(); is just returning the value "0" and I'm not sure why.
There is a column called ID in stores, but if it was grabbing that, the value would be "1". Either way, I wish this method could be written as mysql_insert_SID();
Any idea what I am doing wrong or how I can fix this? And yes, I know this is a deprecated approach, but first I want to figure out how before I worry about converting to PDO.
// Get values from form
$category = $_POST['category'];
$genre = $_POST['genre'];
$story_name = $_POST['story_name'];
$text = $_POST['text'];
$query = "INSERT INTO stories (ID, category, genre, story_name, active) VALUES
('$user_ID', '$category', '$genre','$story_name', '1')";
$result = mysql_query($query);
$SID = mysql_insert_id();
$SID2 = "select stories.SID from stories where stories.SID=$SID";
$query2 = "INSERT INTO writing (ID, SID, text, position, approved)
VALUES('$user_ID', '$SID2', '$text', '1','N')";
$result = mysql_query($query2);
Retrieves the ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT).
(http://php.net/manual/en/function.mysql-insert-id.php)
But you aren't executing any query (via mysql_query()). You're just assigning your query to a variable. Try following:
$query = "INSERT INTO stories (ID, category, genre, story_name, active) VALUES
('$user_ID', '$category', '$genre','$story_name', '1')";
mysql_query($query);
$SID = mysql_insert_id();
I think you've forgotten to execute the query most probably?
Try
$SID = mysql_insert_id();
after executing the query
$query = "INSERT INTO stories (ID, category, genre, story_name, active) VALUES
('$user_ID', '$category', '$genre','$story_name', '1')";
$result = mysql_query($query); // executing
$SID = mysql_insert_id(); // order of queries is important
If you cannot get the value through mysql_insert_id() then try SELECT LAST_INSERT_ID(). Of course there will be a value if you have executed an insert query with AUTOINCREMENT (which you haven't done yet)

PHP - MySQL find row and replace

what im trying to figure out is how do i find something in my MySQL database and then replacing another row. Example
mysqli_query($con,"INSERT INTO persons (FirstName, LastName, Age)
VALUES ('$_POST[custom]', '$_POST[receiver_email]','$_POST[mc_gross]')");
$result = mysqli_query($con,"SELECT * FROM Persons
WHERE FirstName='bjarne'");
mysqli_query($con,"INSERT INTO persons (LastName)
VALUES ('$_POST[item_name]')");
Here i would like it to find where FirstName is "bjarne" and then replace his LastName with '$_POST[item_name]' in this case.
Try this:
$result = mysqli_query($con,"UPDATE `Persons` SET `LastName`='".$_POST['item_name']."'
WHERE `FirstName`='bjarne'");

Not inserting data to database from link

So when someone press this link, it should insert all the data from that text id to a new table but with the username who clicked it and the id of the text the user pressed.
The problem is, when a user clicks the link, it doesn't insert the data, what could be wrong?
The session works, so it must be something with the GET?
<?php
if(isset($_GET['collect'])) {
$perman = $_GET['collect'];
$username = $_SESSION['username'];
$query = $dbh->query("INSERT INTO collections (id, ad, user) VALUES ('', $perman, $username)");
echo 'Saving';
echo $perman;
header ('Refresh: 1; URL=http://localhost/de/collect.php');
}
?>
First, inserting '' for ID isn't very good (don't know if it works), don't use it (uses default), or insert NULL (uses default too, if NOT NULL).
Second, to insert values it's good practice to enquote it and use escape_string on it. I think that's your problem.
$query = $dbh->query("INSERT INTO collections (ad, user) VALUES ('" . $dbh->escape_string($perman) . "', '" . $dbh->escape_string($username) . "')");
You should be doing it like this...if you're using PDO
Much safer, with prepared statements
$sql = "INSERT INTO books (id,ad,user) VALUES (:id,:ad,:user)";
$q = $conn->prepare($sql);
$q->execute(array(':id'=>null,':ad'=>$perman,':user'=>$username));
You tagged your Question with "PDO". Are you using PDO? If yes, why are you not using bindParam() or bindValue()?
If $perman and $username are strings, you've to escape them:
$query = $dbh->query("INSERT INTO `collections` (`id`, `ad`, `user`) VALUES ('', '{$perman}', '{$username}')");
That query should work, but there are still security issues. You've to escape the values. With PDO it's very simple.
General: use http://php.net/manual/en/function.mysql-error.php
Your column "id" should be Integer and have an auto_increment. Of course some IDs are Strings, but if you're able to avoid it, avoid it!
You could print out the $_GET params by using
print_r($_GET);
Edit
Example with PDOStatement::bindValue():
$stmt = $dbh->prepare("INSERT INTO `collections` (`id`, `ad`, `user`) VALUES (:id, :ad, :user)");
$stmt->bindValue(":id", 123);
$stmt->bindValue(":ad", "ad");
$stmt->bindValue(":user", "username");
$stmt->execute();

MySQL Insert from PHP

I'm having a little trouble with my insert statement this morning. Yes, I am using the deprecated mysql_query function. My insert statement looks as follows:
$query3 = "INSERT INTO ".$db_prefix ." offer_det
(fname, lname, 10k, 14k, 18k, 21k, 22k, 24k, 925, coins, bars)
VALUES '".$fname."', '".$lname."', '".$_10k."', '".$_14k."',
'".$_18k."', '".$_21k."', '".$_22k."', '".$_24k."',
'".$_925."', '".$coins."', '".$bars."')";
$result3 = mysql_query($query3);
My PHP form values are all the variables listed in the first part of the insert statement, 'fname', etc.
My variables are set to pull from the post and are listed as the values going into the insert.
I had to change the variables to underscore before they started, I guess PHP didn't like that.
My questions:
Are those 10k, 14k, etc, okay mysql table row names?
Is there an issue I'm missing here?
The datatype for fname and lname are varchar and for the 10k through bars are decimal (7,3).
The column name 925 must be quoted using backticks.
(`fname`, `lname`, `10k`, `14k`, `18k`, `21k`, `22k`, `24k`, `925`, `coins`, `bars`)
You may also want to consider changing the column names to something else to avoid further similar problems in the future.
You should quote the 925 column name, as per MySQL Schema Object names
So correctly:
$query3 = "insert into ".$db_prefix."offer_det (fname, lname, 10k, 14k, 18k, 21k, 22k, 24k, `925`, coins, bars)
values
('".$fname."', '".$lname."', '".$_10k."', '".$_14k."', '".$_18k."', '".$_21k."',
'".$_22k."','".$_24k."', '".$_925."', '".$coins."', '".$bars."')";
Another recommendation: you should escape the incoming strings, because SQL injection is a nasty thing to experience...
Use the QUERY as like follow..
$query3 = "insert into ".$db_prefix."offer_det (fname, lname, 10k, 14k, 18k, 21k, 22k, 24k, 925, coins, bars)
values ('$fname', '$lname', '$_10k', '$_14k', '$_18k', '$_21k', '$_22k',
'$_24k', '$_925', '$coins', '$bars')";
$query_exec=mysql_query($query3) or die(mysql_error());
And for inserting a variable you need to use single codes only..
Can I be bold and suggest a change in your implementation?
/// put your vars in an easier to use format
$insert = array(
'fname' => $fname,
'lname' => $lname,
'10k' => $_10k,
/* and so on ...*/
);
/// considering you are using mysql_query, use it's escape function
foreach ( $insert as $field => $value ) {
$insert[$field] = mysql_real_escape_string($value);
}
/// pull out the keys as fields and the values as values
$keys = array_keys($insert);
$vals = array_values($insert);
/// the following should auto backtick everything... however it should be
/// noted all the values will be treated like strings as you were doing anyway
$query = "INSERT INTO `" . $db_prefix . "offer_det` " .
"(`" . implode('`,`', $keys) . "`) " .
"VALUES ('" . implode("','", $vals ) . "')";

INSERT PHP Statement not working

So, I'm not exactly sure what the problem is, but, when I try to INSERT into a table, it doesn't work.
All the variables are working. I've echoed and tested them, they are working.
$username = $_SESSION['username'];
$update = $_GET['update'];
mysql_query("INSERT INTO updates (username, update) VALUES ('$username', '$update')");
So it must be a problem with my mySQL query. This mySQL query is one of two in the .php folder. If that makes any difference.
Error in SQL
There is an error in your SQL. You cannot use MySQL keywords in column names without quoting them.
In this case update needs to be enclosed in backticks:
$query = "INSERT INTO updates (`username`, `update`)
VALUES ('$username', '$update')";
SQL injection
Your code is susceptible to SQL injection attacks. You should escape quoted strings that are placed into an SQL statement with mysql_real_escape_string() or bind your data using PHP PDO prepared statements.
$username = mysql_real_escape_string($_SESSION['username']);
$update = mysql_real_escape_string($_GET['update']);
Putting it together
$username = mysql_real_escape_string($_SESSION['username']);
$update = mysql_real_escape_string($_GET['update']);
$query = "INSERT INTO updates (`username`, `update`)
VALUES ('$username', '$update')";
I have written little SQLFiddle for you so you can see this in action: http://sqlfiddle.com/#!2/c25b1/1
You need to escape the data you are about to insert. You also want to separate the string from the variables.
Try something like this:
$username = mysql_real_escape_string($_SESSION['username']);
$update = mysql_real_escape_string($_GET['update']);
mysql_query("INSERT INTO `updates` (username, update) VALUES ('" . $username . "', '" . $update . "')") or die(mysql_error());
That's untested but should work.
mysql_error() is the best way but you can also echo your query and run it directly against the database to see what is the problem.
$username = $_SESSION['username'];
$update = $_GET['update'];
$query = "INSERT INTO updates (username, update) VALUES ('$username', '$update')";
mysql_query($query);
echo "My Query : $query";
try this:
$username = $_SESSION['username'];
$update = $_GET['update'];
mysql_query("INSERT INTO updates (username, update) VALUES ('+$username', '+$update')");
also is better is create a variable to put the query string and then you make the query

Categories