SQL query doesn't execute on MSSQL - php

The script receives variable from URL:
if(isset($_GET['string'])){
$string = $_GET['string'];
}
Then I use this variable in sql query:
$sql =
"SELECT
*
FROM
mytable
WHERE
mytable.column_a = '".$string."'";
The problem is that this query doesn't execute, where my variable contains special characters. Example:
/myscript.php?string=a>xxx<P>yy#"
Tried to use both htmlentities() and addslashes(). Also tried to copy/paste echo of the variable - works fine.
How can I solve this problem?

Please, use parameters instead of concatenate query parts. This code should work fine:
<?php
header('Content-Type: text/html; charset=utf-8');
$serverName = "SERVER\INSTANCE";
$connectionInfo = array("Database"=>"Test");
$conn = sqlsrv_connect($serverName, $connectionInfo);
if(isset($_GET['string'])){
$params = array($_GET['string']);
}
if( $conn === false ) {
echo "Unable to connect.</br>";
die(print_r(sqlsrv_errors(), true));
}
$tsql =
"SELECT *
FROM mytable
WHERE column_a = ?";
$stmt = sqlsrv_query($conn, $tsql, $params);
if( $stmt === false ) {
echo "Error in executing query.</br>";
die(print_r(sqlsrv_errors(), true));
}
while ($obj = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC)) {
echo $obj[0];
}
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn);

If column_a is nvarchar datatype try including N before the string quotes.

Try this query
First check $string is getting correct and then try,
$sql =
"SELECT
*
FROM
mytable
WHERE
mytable.column_a = ".$string;

I suggest that you use urlencode — URL-encodes ion your codes, for more information and details you can also have a look at following link:
http://php.net/manual/en/function.urlencode.php

Related

Get ID of Last Entery in MSSQL Server via PHP

Hello i need a little Help.
I have a MSSQL Server and i need the ID of the Last Entery.
My PHP Code is:
$conn = sqlsrv_connect( $serverName, $connectionInfo);
$sqlnextid = "Select IDENT_CURRENT('dbo.Person')";
echo $sqlnextid;
$nextid = sqlsrv_query( $conn, $sqlnextid );
echo $nextid;
Unfortunately $nextid only returns "Resource id#3" and not the correct ID in the SQL Management Studio. The sql query "Select IDENT_CURRENT('dbo.Person')" works fine an give the correct answer - (33).
Where is my mistake? Thanks in advance :)
You need to fetch the data from the executed query uisng sqlsrv_fetch_array(). As is explained in the documentation, the function sqlsrv_query() returns a statement resource or false if the statement cannot be created and/or executed.
As a side note, always check the result from the sqlsrv_connect() and sqlsrv_query() calls.
<?php
...
// Connection
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
echo "Error (sqlsrv_connect): ".print_r(sqlsrv_errors(), true);
exit;
}
// Query
$sqlnextid = "SELECT IDENT_CURRENT('dbo.Person') AS [CurrentIdent]";
$stmt = sqlsrv_query( $conn, $sqlnextid );
if( $stmt === false ) {
echo "Error (sqlsrv_query): ".print_r(sqlsrv_errors(), true);
exit;
}
// Data
$ident = 0;
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$ident = $row["CurrentIdent"];
}
echo $ident;
...
?>
sqlsrv_query returns returns a statement resource on success and FALSE if an error occurred.
You can access the result using sqlsrv_fetch_object.
$sqlnextid = "SELECT IDENT_CURRENT('dbo.Person') AS LastId"
$result = sqlsrv_query($conn, $sqlnextid);
$row = sqlsrv_fetch_object($result)
echo $row->LastId;

SQL - Select doesn't retrieve results

I'm using sqlsrv_num_rows in order to check if a user exists in the DB.
When i'm running the query in my DB i'm getting 1 result, but in my PHP I'm not getting anything (echo doesn't print anything). Why is that?
$query = "SELECT TOP 1 id, tourOp FROM users WHERE (valid = 1) AND (email = '".trim($_POST['email'])."') AND (password = '".trim($_POST['password'])."')";
$stmt = sqlsrv_query( $conn, $query);
echo "num: ".sqlsrv_num_rows( $stmt );
if (!sqlsrv_num_rows( $stmt )) {
return (false);
} else {
}
Example query
SELECT TOP 1 id, name FROM users WHERE (valid = 1) AND (email = 'roi#some_email.com') AND (password = '8521')
I'm using PHP and MSSQL.
Explanations:
Function sqlsrv_num_rows() requires a client-side, static, or keyset cursor, and will return false if you use a forward cursor or a dynamic cursor (the default cursor is forward cursor). Execute sqlsrv_query() with additional $options parameter and set the appropriate cursor type with "Scrollable" => SQLSRV_CURSOR_KEYSET
Use parameterized statements. Function sqlsrv_query() does both statement preparation and statement execution and can be used to execute parameterized queries.
If you want to check if the result set has one or more rows, you may use sqlsrv_has_rows().
Example, based on your code:
<?php
$query = "
SELECT TOP 1 id, tourOp
FROM users
WHERE (valid = 1) AND (email = ?) AND (password = ?)";
$params = array(trim($_POST['email']), trim($_POST['password']));
$options = array("Scrollable" => SQLSRV_CURSOR_KEYSET);
$stmt = sqlsrv_query( $conn, $query, $params, $options);
if ($exec === false){
echo print_r( sqlsrv_errors());
echo "<br>";
return (false);
}
$count = sqlsrv_num_rows($stmt);
if ($count === false) {
echo print_r( sqlsrv_errors());
echo "<br>";
return (false);
} else {
echo "num: ".$count;
}
?>
Notes:
Do not send user credentials in plain text.

php Query a database

I queried an sql server database and got a recordset with 5 rows. I then looped through the recordset doing my output. All was fine when i used:
<?= $row.['Photo'] ?>
to output the value.
When I tried to ask if the value from the database was null, I ran into problems. PHP Notice: Array to string conversion.
if ($row.['Photo'] == "" || $row.['Photo'] == null){
echo $row.['Photo'];
else{
//something else;
}
This was so that if no photo was indicated in the record, I could display something else.
I have researched this and was unable to find the answer. I tried
$photo = strval($row.['Photo']);
$photo = implode("",$row.['Photo']);
Here is my query:
$serverName = "IT-NEWITWEB-D\sqlexpress";
$connectionInfo = array( "Database"=>"eVENTS", "UID"=>"uSER", "PWD"=>"P#\$\$" );
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT tblEvents.EventID, tblEvents.Photo, tblEvents.title, tblLocation.Date, tblLocation.Location, tblEvents.unlist, tblEvents.description, tblEvents.Par_num FROM tblLocation INNER JOIN tblEvents ON tblLocation.Event_ID = tblEvents.EventID GROUP BY tblEvents.EventID, tblEvents.Photo, tblEvents.title, tblLocation.Date, tblLocation.Location, tblEvents.unlist, tblEvents.description, tblEvents.Par_num HAVING (((tblEvents.unlist)>getdate()) AND ((tblEvents.Par_num)=261));";
//$params = array();
$stmt = sqlsrv_query( $conn, $sql);
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
$result = sqlsrv_query($conn, $sql);
while($row = sqlsrv_fetch_array($result)) {
//if photo is empty, display date instead.
}
you're doing wrong, use this $row['Phone']; instead of $row.[];
getting property of Object!
I think that PHP interprets that you are trying to concatenate $row with something else. Try removing the dots "$row.['Phone']".
Another thing that I noticed is that, in your example, you are printing only when the value is empty or null. To do the opposite you should do:
if ($row['Photo'] != "" && $row['Photo'] != null){
echo $row['Photo'];
else{
//something else;
}
Or
if (is_array($row) && !empty($row['Photo'])) {
echo $row['Photo'];
else{
//something else;
}

PHP MySQL Query Where x = $variable from function

Why is this not working:
function listOrderComments ($factnr){
global $connection;
//$factnr = 123; //or $factnr = "123"; (Both work)
$query = "SELECT * FROM orderstatus WHERE factuurnummer = '$factnr'";
$result = mysqli_query($connection, $query);
When I echo $factnr I get "123" back.
When I uncommented //$factnr = 123; my function is working.
Looked everywhere for a solution. check the type $factnr is (string).
Well if you're using a variable in your query you're opening yourself up to an injection attack for one.
If you're going to be using that variable I would recommend you use bind_param for your query
Read the PHP manual link below and you will be able to figure out the issue
http://php.net/manual/en/mysqli-stmt.bind-param.php
If you're passing in a variable to your function it should already be set so I don't understand why you're setting it to 123 anyway. So execute the sql statement and bind the parameter following the first example on the PHP docs page.
public function listOrderComments ($factnr)
{
global $connection;
$query = "SELECT * FROM orderstatus WHERE factuurnummer = ?";
$sql->prepare($query);
$sql->bind_param("s", $factnr);
$sql->execute();
$result = $sql->get_result();
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);
foreach ($data as $row) {
print_r($row);
}
}
Then do what you want with the result
You can go with:
$query = "SELECT * FROM orderstatus WHERE factuurnummer = ". $factnr;
Concatenating your code is not good practise. Your best solution is to use PDO statements. It means that your code is easier to look at and this prevents SQL injection from occuring if malice code slipped through your validation.
Here is an example of the code you would use.
<?php
// START ESTABLISHING CONNECTION...
$dsn = 'mysql:host=host_name_here;dbname=db_name_here';
//DB username
$uname = 'username_here';
//DB password
$pass = 'password_here';
try
{
$db = new PDO($dsn, $uname, $pass);
$db->setAttribute(PDO::ERRMODE_SILENT, PDO::ATTR_EMULATE_PREPARES);
error_reporting(0);
} catch (PDOException $ex)
{
echo "Database error:" . $ex->getMessage();
}
// END ESTABLISHING CONNECTION - CONNECTION IS MADE.
$factnr = "123" // or where-ever you get your input from.
$query = "SELECT * FROM orderstatus WHERE factuurnummer = :factnr";
$statement = $db->prepare($query);
// The values you wish to put in.
$statementInputs = array("factnr" => $factnr);
$statement->execute($statementInputs);
//Returns results as an associative array.
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
$statement->closeCursor();
//Shows array of results.
print_r($result);
?>
Use it correctly over "doted" concat. Following will just work fine:
$factnr = 123;
$query = "SELECT * FROM orderstatus WHERE factuurnummer = " . $factnr;
UPDATE:
here is $factnr is passing as argument that supposed to be integer. Safe code way is DO NOT use havvy functions even going over more complicated PDO, but just verify, is this variable integer or not before any operation with it, and return some error code by function if not integer. Here is no danger of code injection into SQL query then.
function listOrderComments ($factnr){
global $connection;
if (!is_int($factnr)) return -1
//$factnr = 123; //or $factnr = "123"; (Both work)
$query = "SELECT * FROM orderstatus WHERE factuurnummer = " . $factnr;
$result = mysqli_query($connection, $query);

PHP sqlsrv_query select statement not working

I want to make a consult to the MSSQLSERVER with a SELECT STATEMENT but the sqlsrv_query is returning FALSE to me.
I already tested the query and its working fine, am I passing the parameters correctly?
Here is my code:
if($conn === false)
{
die(print_r(sqlsrv_errors()));
}
try
{
$email = "somedbemail#email.com";
$sql = "select Usuario.Email, Usuario.Senha FROM Usuario WHERE Usuario.Email = (?)";
$params = array($email);
$stmt = sqlsrv_query( $conn, $sql, $params);
if($stmt != False)
{
if($row = sqlsrv_fetch_Array($stmt))
{
$email_Con = $row['Email'];
$psw_Con = $row['Senha'];
}
else
{
echo "alguma coisa";
}
}
else
{
echo "It always enters here!";
}
Two possible problems.
The first is the format of your query. You are using:
select Usuario.Email, Usuario.Senha FROM Usuario WHERE Usuario.Email = (?)
Where I think you should be doing:
select Usuario.Email, Usuario.Senha FROM Usuario WHERE Usuario.Email = ?
The second is that the An invalid parameter was passed to sqlsrv_query() message is common when the connection is not correct (Reference). So double check that your connection is a valid resource.

Categories