This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 8 years ago.
I have a challenge getting a query i saved into the database.
On my project, i want to save mysql update query in the database, and when another action is run on a different page, i get that query and pass it through my function and it runs. However after getting it its empty. Below is what i have done so far.
//Saving the query in database
$query = array();
$query['approved'] = "UPDATE payment SET pm_status = 'Approved' WHERE id = '69'";
$query['approved2'] = "UPDATE member SET pay_date = NOW())";
//i den serialize and addslashes so it can be saved in the database
$tosave = addslashes(serialize($query));
$sql = "INSERT INTO trans (saved_query) VALUES ($tosave)";
// I den save $tosave into the database, which i checked and it was saved.
On the page i want to use it, each time i get the value and unserialize, it returns as empty e.g after selecting the value to a row
$toprocess = unserialize($query['saved_query']);
echo $toprocess['approved'];
it returns an empty value, and when i run it in a query it doesn't run.
but if i echo directly without unserializing, it dispplays the values in it
echo $query['saved_query'];
Pls help incase i am missing something here. Thanks
I am not preventing an sql injection. I had dont that already. I just want to run the sql saved into the database. This is different to the answers in the prevention of mysql injection. Thanks
There is an error in your query
$query['approved2'] = "UPDATE member SET pay_date = NOW())";
there is an extra bracket with now() function.
Related
This question already has answers here:
MySQL Insert query doesn't work with WHERE clause
(31 answers)
Closed 4 years ago.
I am trying to run a basic SQL statement, but I can't figure out what I am doing wrong. Here is the context:
I have a database named: my_database
a table named: users
Two columns: service_id which type is BIGINT
and video_id which type is varchar(20)
Here is my code:
$video_id = "chartext";
$service_id = 12345678910;
$bdd = new PDO("mysql:host=127.0.0.1;dbname=moods_db", "user", "pass");
$query = $bdd->prepare("INSERT INTO users(video_id) VALUES (?) WHERE service_id = $service_id");
$query->execute([$service_id]);
var_dump($req->execute([$video_id]));
// which gives me false
Some info:
My PHP_INT_MAX gives me 9223372036854775807
I am aware of SQL Injection and just removed it to be clearer
I var_dumped each steps and the execute one is the only one that is not working
I ran the statement in phpmyadmin console and it told me: "Syntax error near 'WHERE (service_id = '12345678910')' line 1
I also searched the usage of WHERE Clause but I did not understand if I could put it in an INSERT statement, I think I already did that and it worked, I am lost
Thanks in advance
PDOStatement::execute — Executes a prepared statement. It returns TRUE on success or FALSE on failure.
So for your case it is returning FALSE because In an INSERT statement you wouldn't have an existing row to do a WHERE clause.
You need to try like this way to insert one row with two values or use UPDATE query to update one row with one value based on another value on the existing row. Hope it clears your doubts now :)
$video_id = "chartext";
$service_id = 12345678910;
$bdd = new PDO("mysql:host=127.0.0.1;dbname=moods_db", "user", "pass");
$sql = "INSERT INTO users(video_id, service_id) VALUES (?,?)";
$array = array($video_id , $service_id );
$sth = $bdd->prepare($sql);
$sth->execute($array);
var_dump($sth);
Actually you can't use WHERE Clause with INSERT TO.
Here are some answers, https://stackoverflow.com/a/11913305/7183227 https://stackoverflow.com/a/485057/7183227
from MySQL Insert Where query
The problem is with the way you have written INSERT query. INSERT query does not contain where clause.
You have to update it your query as follows:
INSERT INTO users(video_id) VALUES (?)
You shouldn't use WHERE clause in INSERT query. so, either perform INSERT (it does not have WHERE) or try UPDATE where you can use WHERE clause. just visit here https://phpdelusions.net/pdo_examples/insert if you want to insert the record or here https://phpdelusions.net/pdo_examples/update if you want to update and check the syntax and perform it properly. :)
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 4 years ago.
I have a value in my MYSQL database, all I want to do is to increase the current value with a new one, this is what I have tried
} elseif ($gametype == "veckanskluring"){
$sql = "UPDATE users SET veckanskluring='veckanskluring'+'$score' WHERE id='$id'";
$retval = mysql_query( $sql, $link );
echo "GAME == $gametype";
}
But for some odd reason, this won't work.
I have searched online and found examples, but they all look, almost exactly the same as my code.
// Sidenote this is not the whole code, obviously.
Everything except the part where I add the new value to the old value works, and if I remove 'veckanskluring'+ it updates without any problems.
I strongly believe something is wrong with this part - 'veckanskluring'+ as the other part works fine.
//NOTE2 score is always 999, just have it set to $score if I want to change it later.
UPDATE -
MY fault, apparently I had put '' around veckanskluring.
$sql = "UPDATE users SET veckanskluring=veckanskluring +'$score' WHERE id='$id'"; <-- Working.
Assuming that $score and $id are number you shoudl not use sigle quote around this vars
and assuming that veckanskluring is column name you must not use single quote aroud column name
"UPDATE users SET veckanskluring= veckanskluring +$score WHERE id=$id";
But the use of php var in sql is deprecated you at risk for sql injection .. take a look at your mysql driver for bindig param
This question already has answers here:
mysqli last insert id
(3 answers)
Closed 5 years ago.
I am executing the following sql code
$query = "INSERT INTO order_shipping_addresses(user_customer_id, shipping_address_details, created, modified) VALUES('".$_SESSION['user_id']."', '".serialize($address)."', '".$created."', '".$modified."')";
$connection = $this->establish_connection();
$data = $connection->query($query);
$order_shipping_address_id = last_insert_id();
$connection->close();
What i wanted was when this query is executed i wanted the row id in which this data is inserted, i am using the last_insert_id() function but i am getting an error of Call to undefined method mysqli::lastInsertId()
how to extract all the data from the $data variable and also the row id in which the data is inserted. I am using PHP OOP style.
Thanks in advance..
You want to use $connection->insert_id
This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 9 years ago.
I've below code in one of my php files to fetch data from DB:
$products = $this->db->get_rows('SELECT * from products WHERE shop_id='.$_SESSION['shop_id'].'AND tags,title,text LIKE \'%'.$_POST['search'].'%\'');
Is it problematic? I mean LIKE operator can be injected?
Edited
please provide examples of injecting in this way
Any operator can be injected without binding.
$_POST['search'] = "1%'; DROP TABLE myTable LIKE '%";
Would make
.... AND tags,title,text LIKE '%1%'; DROP TABLE myTable LIKE '%%'
Read on how to bind parameters.
Of course this can be injected, you need to sanitize your input. Right now you are taking raw post data and inserting it into your SQL statement.
You should run your POST data through some sort of data sanitization, something like mysql_real_escape_string or the like
Or at least prepared statements. let server side code do the work for you.
Never, ever, use database queries like that, don't construct a string with variables and use it for database activities.
Construct a string that will later on be prepared and executed, by inserting the variables into the string, making them not act like "commands" but as "values".
You can do it like this:
$query = "SELECT * from products WHERE shop_id = :shopId;"; // An example, you can finish the rest on your own.
Now, you can prepare the statement (I recommend using PDO for this).
$statement = $db->prepare($query); // Prepare the query.
Now you can execute variables into the prepared query:
$statement->execute(array(
':shopId' => $_SESSION['shop_id']
));
If you're inserting or updating, then you would have wanted to do:
$success = $statement->execute(array(
':shopId' => $_SESSION['shop_id']
));
which stores a boolean in $success, or you can fetch the values from a result if you're SELECTing:
$statement->execute(array(
':shopId' => $_SESSION['shop_id']
));
$result = $statement->fetch(PDO::FETCH_ASSOC);
if($result )
{
// You can access $result['userId'] or other columns;
}
Note that you should actually make that be a function, and pass $shopId into the function, but not the session itself, and check if the session actually exists.
I recommend googling on how to use PDO, or take a look on one of my examples: How to write update query using some {$variable} with example
This is really bad. Pulling vars into an SQL statement without cleaning or checking them is a good way to get pwnd. There are several things that people can inject into code. Another injection method to watch out for, 1=1 always returns true.
$products = $this->db->get_rows('SELECT * from products WHERE shop_id='.$_SESSION['shop_id'].'AND tags,title,text LIKE \'%'.$_POST['search'].'%\'');
//This example expects no result from the table initially so we would blind attack the DB to pull the admin record.
$_POST['search'] = "-1\'; union all select * from users limit 1;";
Someone call pull up the top account in the database (like the admin).
$user_id = $this->db->get_rows('SELECT * from users WHERE email="'.$_POST['email'].'" and password="'.$_POST['password'].'"');
//This always returns true so now I'm the admin again
$_POST['password'] = "x\' or 1=1 limit 1";
You also want to be careful what you print on screen.
$user_id = $this->db->get_rows('SELECT * from users WHERE email="'.$_POST['email'].'" and password="'.$_POST['password'].'"');
A message that you echo that says "No user name exists for $_POST['email']" could be replaced with something else.
$_POST['email']=";
$fp = fopen('index.php', 'w');
fwrite($fp, \"header('Location: http://badwebsite.com;');\";
fclose($fp);";
index.php could now people to a different website entirely where an infected page exists or an infected page on the site.
If you're checking IDs do something like:
if(preg_match('!^[0-9]$!',$_POST['id'])){
$id = $_POST['id'];
} else {
//flush
}
or count for the number of possible records... if you're only expecting one and you get all of the records in the DB then it's an injection attempt.
if(is_numeric($_POST['id'])){
$id = $_POST['id'];
$count = mysql_result(mysql_query("select count(*) from users where id='$id''),0);
}
This question already has answers here:
How to get Insert id in MSSQL in PHP?
(3 answers)
Closed 10 years ago.
I want to get last inserted id of particular table. can any one tell me how i can get that?
we have mysql_insert_id() in mysql. Do we have similar kind of function in sql server 2008?
something like this works very nicely
$sql = "insert into tables(field) values (value);SELECT SCOPE_IDENTITY()";
$db = getConnection();
$results = mssql_fetch_assoc(mssql_query($sql));
$lastid=$results['computed'];
I made this function to make it easy :)... if you have more then one db resource just pass that into the mssql_query request. This will retrieve the last unique id generated on that resource connection.
mssql_query("insert into data(name) values('bob')");
$id = getLastId();
function getLastId() {
$result = mssql_fetch_assoc(mssql_query("select ##IDENTITY as id"));
return $result['id'];
}