$_GET[] a value via jquery to php SQL statement - javascript

Below is the jQuery to passing the attr() value to $_GET[]. When I echo $_GET[] it displays the value. But not when I pass the $_GET into a MySQL statement.
$('.DetailsDisplay').click(function() {
var ix = $(this).attr('id');
$('#Details').load('details.php?regid='+ix);
});
details.php
mysql_select_db($database_host, $host);
$query_list_class = "SELECT * FROM xfi where no='".stid."'";
$list_class = mysql_query($query_list_class, $sshost) or die(mysql_error());
$row_list_class = mysql_fetch_assoc($list_class);
Any idea why?

You've got no $ sign in sql
$query_list_class = "SELECT * FROM xfi where no='".$stid."'";
PS: Also please parse $stid to int
$stid = (int) $_GET['regid'];

you forgot $ sign
also make sure to prevent sql injection
$stid = intval($_GET['regid']);
$query_list_class = "SELECT * FROM xfi where no='".$stid."'";
note : don't use mysql_* functions, they are deprecated, use PDO or mysqli instead

Related

Javascript evaluation failed in karate framework [duplicate]

def query = read(intitation.sql);
string output = query
I want to parameterize and the pass the column2 ='value' dynamically from feature file, can you help me in how to achieve this.
Below is the sql file intitation.sql:
SELECT column1, column2, column3, column4, column5, column6, column7, column8, column9, column10, column11, column12 FROM table1 WHERE **column2='value'**;
This is normal JS fundamentals:
* def value = 'foo'
* def sql = "select * from dogs where name = '" + value + "'"
Also see replace if it helps: https://github.com/intuit/karate#replace
EDIT: also see https://stackoverflow.com/a/71063078/143475
Maybe this would also work? Just something to chew on as being an interesting solution. On more complicated parameterizations, this could work well.
* def String = Java.type('java.lang.String')
* def pString = "Select * from Whatever where id = '%s' and name = '%s'"
* def query = String.format(pString, "my-id", "my-name")
Also, could perhaps load the Java PreparedStatement class?

How do I make a PG SQL ilike query in Javascript injection safe? [duplicate]

I am using prepared statements to execute mysql database queries. And I want to implement a search functionality based on a keyword of sorts.
For that I need to use LIKE keyword, that much I know. And I have also used prepared statements before, but I do not know how to use it with LIKE because from the following code where would I add the 'keyword%'?
Can I directly use it in the pstmt.setString(1, notes) as (1, notes+"%") or something like that. I see a lot of posts on this on the web but no good answer anywhere.
PreparedStatement pstmt = con.prepareStatement(
"SELECT * FROM analysis WHERE notes like ?");
pstmt.setString(1, notes);
ResultSet rs = pstmt.executeQuery();
You need to set it in the value itself, not in the prepared statement SQL string.
So, this should do for a prefix-match:
notes = notes
.replace("!", "!!")
.replace("%", "!%")
.replace("_", "!_")
.replace("[", "![");
PreparedStatement pstmt = con.prepareStatement(
"SELECT * FROM analysis WHERE notes LIKE ? ESCAPE '!'");
pstmt.setString(1, notes + "%");
or a suffix-match:
pstmt.setString(1, "%" + notes);
or a global match:
pstmt.setString(1, "%" + notes + "%");
We can use the CONCAT SQL function.
PreparedStatement pstmt = con.prepareStatement(
"SELECT * FROM analysis WHERE notes like CONCAT( '%',?,'%')";
pstmt.setString(1, notes);
ResultSet rs = pstmt.executeQuery();
This works perfectly for my case.
Code it like this:
PreparedStatement pstmt = con.prepareStatement(
"SELECT * FROM analysis WHERE notes like ?");
pstmt.setString(1, notes + "%");`
Make sure that you DO NOT include the quotes ' ' like below as they will cause an exception.
pstmt.setString(1,"'%"+ notes + "%'");
PreparedStatement ps = cn.prepareStatement("Select * from Users where User_FirstName LIKE ?");
ps.setString(1, name + '%');
Try this out.
String fname = "Sam\u0025";
PreparedStatement ps= conn.prepareStatement("SELECT * FROM Users WHERE User_FirstName LIKE ? ");
ps.setString(1, fname);
String query="select * from test1 where "+selected+" like '%"+SelectedStr+"%';";
PreparedStatement preparedStatement=con.prepareStatement(query);
// where seleced and SelectedStr are String Variables in my program

AJAX / jQuery / PHP / MySQL - how to update a database

I need to update a database using AJAX so don't have my page be reloaded. I can't find what's wrong and unexpectedly I get a success message back but a database doesn't get updated.
JS:
$('.start-time-class').submit(function() {
var startTime = "11:30";
var projectID = 17;
var userID = 2;
$.ajax({
url:'functions/starttime.php',
data:{startTime:startTime,projectID:projectID,userID:userID}, // pass data
dataType:'json',
success:function(){
// something
}
});
});
PHP:
$con = mysqli_connect('localhost','smt','smt','smt');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
$startTime = $_GET['startTime'];
$projectID = $_GET['projectID'];
$userID = $_GET['userID'];
mysqli_select_db($con,"ajax_demo");
$sql = "INSERT INTO 'uc_project_time'('userID', 'projectID', 'startTime') VALUES (". $userID .", ". $projectID .", ". $startTime .")";
$result = mysqli_query($con,$sql);
mysqli_close($con);
Don't use quotes for table or column names
Use:
$sql = "INSERT INTO uc_project_time (userID, projectID, startTime) VALUES ('$userID', '$projectID', '$startTime')";
or
$sql = "INSERT INTO uc_project_time (userID, projectID, startTime) VALUES ('".$userID."', '".$projectID."', '".$startTime."')";
And do sanitize your code:
How can I prevent SQL injection in PHP?
You don't use quotes(single or double) in SQL for table or column names. You could use backticks(`), though not necessary(in your circumstance), it can be required in some situations.
When to use backticks(`)?
Firstly, you'd only use them in MySQL, as SQL Server and T-SQL use square brackets [] to denote identifiers.
If you were using spaces or keywords in your column or table names, you would need backticks. This would instruct the parser to parse the column or table name as a literal string.
To illustrate, if you had a table called 'badly named table'.
This wouldn't work
SELECT FROM badly named table...
This would work
SELECT FROM `badly named table`...
To conclude, backticks are useful if you have a bad table or column naming convention.
SQL Injections
Also, as #Fred -ii- said you're currently vulnerable to SQL Injections. If you're using PHP with PDO enabeled, you could use the following code (with prepared statements) protect against SQL injections and ensure that malicious actions can't be carried out on your database.
$con = new PDO('mysql:host=localhost; dbname= name_of_db', 'name_of_user', 'password_of_user');
$sql = $con->
prepare("
INSERT INTO uc_project_time userID, projectID, startTime VALUES (:userID, :projectID, :startTime)
");
$sql->bindParam(':userID', $userID,':projectID', $projectID,':startTime', $startTime, PDO::PARAM_STR);
$sql->execute();
$rows = $sql->fetchAll(PDO::FETCH_ASSOC);
Or, If you want to continue using MySQLi, you could use their version of prepared statements. That said, I recommend PDO for the reasons illustrated here.

Save javascript value as plaintext in DB

This is the problem I get, for example, when an user inputs <script>top.location.href=’http://www.google.nl’;</script>
I want my application to echo it as plain text. Now, this actually works with
htmlspecialchars()
This example works for me:
$test = "<script>top.location.href=’http://www.google.nl’;</script>";
echo htmlspecialchars($test);
But, when the user submits the form, the data goes to my DB and then returns to a 'dashboard'.
The value is now ''.
Is there a way how I can save the data safe into my DB?
I add the values into the DB for my C# application in this way via SDK:
$onderwerp = htmlspecialchars(stripslashes(trim($_POST['onderwerp'])), ENT_QUOTES,'UTF-8',true);
$omschrijving = htmlspecialchars(stripslashes(trim($_POST['omschrijving'])), ENT_QUOTES,'UTF-8',true);
$im = array('description' => mysql_real_escape_string($onderwerp),
'message' => mysql_real_escape_string($omschrijving) ,
'relation' => $_SESSION['username'],
'messageType' => 70,
'documentName' => $_FILES["file"]["name"],
'documentData' => base64_encode(file_get_contents($_FILES["file"]["tmp_name"])));
$imresponse = $wcfclient->CreateInboundMessage($im);
echo $imresponse->CreateInboundMessageResult;
And then call them at my dashboard in this way:
$roc = array('relation' => $_SESSION['username']);
$rocresponse = $wcfclient->ReadOpenCalls($roc);
foreach ($rocresponse->ReadOpenCallsResult as $key => $calls){
echo $calls->Description;
}
can you please check mysql-real-escape-string
mysql_real_escape_string() :
The mysql_real_escape_string() function escapes special characters in a string for use in an SQL statement
Also CHeck SQL Inject :SQL Injection
Example
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$item = "Zak's and Derick's Laptop";
$escaped_item = mysql_real_escape_string($item);
printf ("Escaped string: %s\n", $escaped_item);
?>
Ouput :
Escaped string: Zak\'s and Derick\'s Laptop
Yes, read about mysqli_real_escape_string.

How to seperate the datas when jquery get them from mysql?

ChkNewRspLive.php
<?php
$query3 = "SELECT msgid, id FROM rspnotificationlive WHERE username='{$username1}' ORDER BY id LIMIT 99";
$result3 = mysql_query($query3,$connection) or die (mysql_error());
confirm_query($result3);
$numrspmsg = mysql_num_rows($result3);
echo $numrspmsg . "|";
while($userinfo3 = mysql_fetch_array($result3)){
$rspmsgid= $userinfo3['msgid'];
$msgid= $userinfo3['id'];
echo $rspmsgid . ", ";
}
?>
index.html
<script type="text/javascript">
$.get("ChkNewRspLive.php?username=" + username, function(newrspmsg){
var mySplitResult = newrspmsg.split("|");
var rspMsgCount = parseFloat(mySplitResult[0]);
var rspMsgids =(mySplitResult[1]);
var Msgids = ??//how to get this result from ChkNewRspLive.php ?
});
</script>
As you can see, I used "|" to separate $rspmsgid and $numrspmsg. I also use "," to separate multiple $rspmsgid. How if I want to separate another data $msgid? How to do that?
If I use | to separate $rspmsgid and $msgid, there will be many sign of | because they both are in the while loop.
JSON encode your content.
In your php, change your code to something like:
$json = array();
while($userinfo3 = mysql_fetch_array($result3)){
$rspmsgid= $userinfo3['msgid'];
$msgid= $userinfo3['id'];
$json[] = array($rspmsgid,$msgid);
}
echo json_encode($json);
and then use $.getJson in your javascript.
You won't have to define the number of mysql_rows either, as you can just get that in javascript by using .length on the json data.
edit and escape your string before using it in your SQL!
You are already using the .split() method to seperate the other string. Apply it to the other part and let it split by ", " or just use another | instead of the , and you will have it split into three parts instead of two.
However I suggest you have a look at JSON. This should be the better solution if it gets more complicated.

Categories

Resources