I'm trying to show a demo on SQL injection but doesn't seem to work. I have tried to truncate a table named demo with this: "SELECT * FROM products WHERE booktitle like '%'Songs'; TRUNCATE TABLE demo --%'" but is not working.
I'm using MySQL with Nodejs and here is the code:
app.post("/api/productsearch", (req, res) => {
db.query(`SELECT * FROM products WHERE booktitle like '%${req.body.searchData.booktitle}%'`, (err, result) => {
if (err) {
console.log(err);
} else {
res.json(result);
}
}
)
})
How do I do a SQL injection on the productsearch api? Many thanks in advance and greatly appreciate any helps. Thanks
If you enter booktitle as '; TRUNCATE TABLE demo -- , then the resulting SQL statement is
SELECT * FROM products WHERE booktitle like '%'; TRUNCATE TABLE demo -- %'
Related
I would like to find items in a Prisma db where the values for two columns are the same. The use case is to compare the 'created_at' and 'updated_at' fields to find items that have never been updated after their initial creation. In raw SQL I would do something like:
select updated_at,
cast(sign(sum(case when updated_at = created_at then
1
else
0
end)) as int) as never_modified
from tab
group by updated_at
Is it possible to achieve this in Prisma?
You would need to use Raw Queries to compare time values from the same table.
Here's an example of how you could achieve this, assuming a PostgreSQL database for the following query.
import { PrismaClient } from '#prisma/client'
const prisma = new PrismaClient()
async function initiateDatesComparisonRawQuery() {
const response =
await prisma.$queryRaw`SELECT * FROM "public"."Project" WHERE "created_at" = "updated_at";`;
console.log(response);
}
await initiateDatesComparisonRawQuery();
you can use the preview feature fieldReference of prisma.
schema.prisma
generator client {
provider = "prisma-client-js"
previewFeatures = ["fieldReference"]
}
your code
prisma.project.findMany({
where: { created_at: prisma.project.fields.updated_at }
})
I have a query in mysql works well, but when I go to postgresql does not update me, I want to know where is my error.
I leave my php file the query update does not work
<?php
require_once "Controllers/conexion.php";
session_start();
$resultado=pg_query("SELECT nextval('user_id_seq') as key");
$row=pg_fetch_array($resultado, 0);
$key=$row['key'];
try {
$resultado = pg_query($conexion,"select * from encuesta_respuesta where id_user = '".$_SESSION['user']."' and id_encuesta = '".$_POST['id_encuesta']."'");
while( $row = pg_fetch_assoc($resultado)){
$data = $row;
}
if ($data['estado']=='F') {
header("Location: Inicio.php");
}
foreach($_POST['pregunta'] as $id_pregunta=>$valor){
$query="insert into encuesta_respuesta_opcion values (".$key.",".$_POST['id_encuesta'].",".$id_pregunta.",".$valor.")";
$resultado = pg_query($conexion,$query);
}
$query="update encuesta_respuesta set estado='F' where id_user=".$_SESSION['user']." and id_encuesta = ".$_POST['id_encuesta'];
$resultado = pg_query($conexion,$query);
$resp['error']=false;
} catch (Exception $e) {
$resp['error']=true;
}
header("Location: Inicio.php");
?>
Directly try to update data in your database, check this query works or not. If it works, then you have to change your query building procedure in your application. For example:
postgres=# create table test (id_user VARCHAR (50) PRIMARY KEY, id_encuesta VARCHAR (50), estado VARCHAR (10));
postgres=# insert into test values ('anower','engg.','A');
postgres=# update test set estado='F' where id_user='anower' and id_encuesta='engg.';
The query should work the same in MySql and postgres.
If you are getting different results during updates then your survey tables arent the same.
Most liked id_user and id_encuesta are autoincrement fields. So they dont necesary have the same values.
Try using a Select to see if they have same survey information.
SELECT *
FROM survey
where id_user=".$_SESSION['user']."
and id_encuesta = ".$_POST['id_encuesta'];
I am trying to fetch data from two tables using a join. The problem is forum_posts will contain several items with the same thread_id. I would only like to get the first one, either by id or by creating date.
function getByGroup(groupId) {
return knex('forum_threads')
.select('forum_threads.id', 'forum_threads.updated_at', 'forum_posts.content')
.where('forum_threads.group_id', '=', groupId)
.leftJoin('forum_posts', function() {
this.on('forum_posts.thread_id', '=', 'forum_threads.id');
})
.orderBy('updated_at', 'desc')
.then(function(threads) {
return threads;
});
}
I would like to add a limit(1) or a min to the join but not entirely sure how to do it.
You need to add a filter like the following to your left join criteria:
.andOn('forum_posts.created_at', '=', knex.raw("(select min(created_at) from forum_posts where forum_posts.thread_id = forum_threads.id)"))
This says to include the forum post record (as a left join match) if it has the minimum updated_at value for that id.
The full code. The below code isn't tested, although I did test the above snippet in a piece of my code.
function getByGroup(groupId) {
return knex('forum_threads')
.select('forum_threads.id', 'forum_threads.updated_at', 'forum_posts.content')
.where('forum_threads.group_id', '=', groupId)
.leftJoin('forum_posts', function() {
this.on('forum_posts.thread_id', '=', 'forum_threads.id')
/* The new line here */
.andOn('forum_posts.created_at', '=', knex.raw("(select min(created_at) from forum_posts where forum_posts.thread_id = forum_threads.id)"))
})
.orderBy('updated_at', 'desc')
.then(function(threads) {
return threads;
});
}
Cheers!
PS: You didn't ask, but something I find very helpful when debugging Knex is the .on() query reporting clauses:
// ...
.orderBy('updated_at', 'desc')
/* your code above */
.on('query', function(data) {
// outputs the SQL query you generated & runtime data bindings.
console.log(data);
})
.on('query-error', function(error, obj) {
// outputs the Knex failed query, data, etc.
console.log("Error:", error);
console.log("Object: ", obj);
})
/* your code below */
.then(function(threads) {
return threads;
});
I am attempting to effect a join query in node-postgres (pg) with the following function but am getting a syntax error. The problem is the join query, everything else works fine. What is the correct way to format a join query in pg?
exports.bigBook = function(req, res) {
var bookNumber = req.params.id;
pool.connect(function(err, client, done) {
if (err) { return console.error('error fetching client from pool', err);}
client.query('SELECT * FROM book WHERE id = $1 LEFT JOIN author
ON (book.author = author.auth_id)'), [bookNumber], function (err, results) {
client.release();
res.send(results.rows);
};
})
}
The LEFT JOIN is part of the FROM clause, so you'll have to move the WHERE clause to the end of the query.
I am trying:
if (process.NODE_ENV === 'test') {
foreignKeyChecks = 0;
forceSync = true;
} else {
foreignKeyChecks = 1;
forceSync = false;
}
global.db.sequelize.query("SET FOREIGN_KEY_CHECKS = " + foreignKeyChecks).then(function() {
return global.db.sequelize.sync({
force: forceSync
});
}).then(function() {
return global.db.sequelize.query('SET FOREIGN_KEY_CHECKS = 1');
}).then(function() {
var server;
console.log('Initialzed database on:');
console.log(config.db);
return server = app.listen(port, function() {
return console.log("Server listening at http://" + (server.address().address) + ":" + (server.address().port));
});
})["catch"](function(err) {
return console.log('err', err);
});
module.exports = app;
But I get: SequelizeDatabaseError: unrecognized configuration parameter "foreign_key_checks"
I assume I can't have that keyword in postgres? But is there an equivalent way to drop all tables and recreate?
This is an updated answer, targeted at the googlers who wound up here like me.
Sequelize offers a drop function:
drop(options) => promise
Drop all tables defined through this sequelize instance. This is done by calling Model.drop on each model. Sequelize docs
Example
var sequelize = new Sequelize(config.database, config.username, config.password, config);
var someModel = sequelize.define('somemodel', {
name: DataTypes.STRING
});
sequelize
.sync() // create the database table for our model(s)
.then(function(){
// do some work
})
.then(function(){
return sequelize.drop() // drop all tables in the db
});
For wiping out data and create all again from scratch (like in tests):
sequelize.sync({force: true});
I don't know anything about that JavaScript library, but Postgres provides a single command to drop everything that is owned by a user:
drop owned by <our_user_name cascade
This will only work if everything is owned by the same user and that user doesn't have some tables (or views, sequences, ...) that you do not want to drop.
More details in the manual:
http://www.postgresql.org/docs/current/static/sql-drop-owned.html
For anyone looking for a solution with sequelize-cli checkout this link Sequelize CLI:
You can just run:
sequelize_cli db:drop
sequelize_cli db:create
To create or drop your db using the cli tool. This way you will have a empty db.