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.
Related
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.
When I try to add something to the sqlite databse the result is always false. Where is the error? I don't get an exception so I think the code is correct by syntax. Please help me
public function add(ChatMessage $chatMessage){
$stmt = $this->db->prepare('INSERT INTO chatmessage(id,authorName,message) VALUES(:id,:authorName,:message)');
$stmt->bindParam(':id',$id);
$stmt->bindParam(':authorName',$authorName);
$stmt->bindParam(':message',$message);
$id = $chatMessage->getID();
$authorName = $chatMessage->getAuthorName();
$message = $chatMessage->getMessage();
$result = $stmt->execute();
if($result == false) return false;
$chatMessage->setID($this->db->lastInsertId());
$chatMessage->setAuthorName($this->db->lastInsertId());
$chatMessage->setMessage($this->db->lastInsertId());
$this->chatMessages[]=$chatMessage;
}
I have an old PHP code that has mysql in it.
It gets an array from a SELECT statement, adds it to a JSON object, as a property and echoes the encoded JSON.
I changed it around to use mysqli, but when I try to get the rows, and create an array out of them, it just returns nothing.
Here's the old mysql code:
$con = mysql_connect('host','account','password');
if (!$con)
{
//log my error
};
mysql_select_db("database_name", $con);
mysql_set_charset('utf8');
$sql = "SELECT field1 as Field1, field2 as Field2 from table where ID = '".$parameter."'";
$query = mysql_query($sql);
$results = array();
while($row = mysql_fetch_assoc( $query ) )
{
$results[] = $row;
}
return $results;
Version1: Here's the new one that I tried writing:
$con = mysqli_connect('host','account','password','database_name');
$sql = "SELECT field1 as Field1, field2 as Field2 from table where ID = '".$parameter."'";
$results = array();
if($result=mysqli_query($con, $sql))
{
while ($row=mysqli_fetch_assoc($result))
{
$results[] = $row;
}
return $results;
}
else
{
//error
}
Version2: Second thing I tried, which only returns 1 ROW:
...same as above until $sql
if($result=mysqli_query($con,$sql))
{
$row=mysqli_fetch_assoc($result);
return $row;
}
Version3: Or I tried to completely mirror the mysql structure like this:
$sql = "SELECT ...";
$query = mysqli_query($con, $sql);
$results = array();
while($row = mysqli_fetch_assoc( $query ) )
{
$results[] = $row;
}
return $results;
Wrapping the resulting array into the JSON:
$obj = new stdClass();
$obj->Data = $results;
$obj->ErrorMessage = '';
die(json_encode($obj)); //or echo json_encode($obj);
None of the mysqli version are working, so I was thinking there might be an important change in the way these arrays are created.
Any tips on what could be wrong on the first mysqli example?
With Version2 I can tell that the SQL connection is there, and I can at least select a row. But it's obviously only one row, than it returns it. It makes me think, that building up the array is the source of the problem, or it's regarding the JSON object...
LATER EDIT:
OK! Found a working solution.
ALSO, I played around with the data, selected a smaller chunk, and it suddenly worked. Lesson from this: the function is not responding the same way for 40 rows or for 5 rows. Does it have something to do with a php.ini setting? Or could there be illegal characters in the selection? Could it be that the length of a 'Note' column (from the db) is too long for the array to handle?
Here's the working chunk of code, that selects some rows from the database, puts them into an array, and then puts that array into an object that is encoded into JSON at the end, with a statusmessage next to it. Could be improved, but this is just for demo.
$con = mysqli_connect('host','username','password','database_name');
if (!$con)
{
$errorMessage = 'SQL connection error: '.$con->connect_error;
//log or do whatever.
};
$sql = "SELECT Field1 as FieldA, field2 as FieldB, ... from Table where ID='something'";
$results = array();
if($result = mysqli_query($con, $sql))
{
while($row = mysqli_fetch_assoc($result))
{
$results[] = $row;
}
}
else
{
//log if it failed for some reason
die();
}
$obj->Data = $results;
$obj->Error = '';
die(json_encode($obj));
Question is: how can I overcome the issue regarding the size of the array / illegal characters (if that's the case)?
Your "Version 1" seems to be correct from a PHP perspective, but you need to actually handle the errors - both when connecting and when performing the query. Doing so would have told you that you don't actually query a table, you're missing FROM tablename in the query.
Use mysqli_connect_error() when connecting, and mysqli_error($con) when querying to get back the actual errors. General PHP error-reporting might also help you.
The code below assumes that $parameter is defined prior to this code.
$con = mysqli_connect('host','account','password','database_name');
if (mysqli_connect_errno())
die("An error occurred while connecting: ".mysqli_connect_error());
$sql = "SELECT field1 as Field1, field2 as Field2
FROM table
WHERE ID = '".$parameter."'";
$results = array();
if ($result = mysqli_query($con, $sql)) {
while ($row = mysqli_fetch_assoc($result)) {
$results[] = $row;
}
return $results;
} else {
return mysqli_error($con);
}
Error-reporing
Adding
error_reporting(E_ALL);
ini_set("display_errors", 1);
at the top of your file, directly after <?php would enable you to get the PHP errors.
NOTE: Errors should never be displayed in a live environment, as it might be exploited by others. While developing, it's handy and eases troubleshooting - but it should never be displayed otherwise.
Security
You should also note that this code is vulnerable to SQL-injection, and that you should use parameterized queries with placeholders to protect yourself against that. Your code would look like this with using prepared statements:
$con = mysqli_connect('host','account','password','database_name');
if (mysqli_connect_errno())
die("An error occurred while connecting: ".mysqli_connect_error())
$results = array();
if ($stmt = mysqli_prepare("SELECT field1 as Field1, field2 as Field2
FROM table
WHERE ID = ?")) {
if (mysqli_stmt_bind_param($stmt, "s", $parameter)) {
/* "s" indicates that the first placeholder and $parameter is a string */
/* If it's an integer, use "i" instead */
if (mysqli_stmt_execute($stmt)) {
if (mysqli_stmt_bind_result($stmt, $field1, $field2) {
while (mysqli_stmt_fetch($stmt)) {
/* Use $field1 and $field2 here */
}
/* Done getting the data, you can now return */
return true;
} else {
error_log("bind_result failed: ".mysqli_stmt_error($stmt));
return false;
}
} else {
error_log("execute failed: ".mysqli_stmt_error($stmt));
return false;
}
} else {
error_log("bind_param failed: ".mysqli_stmt_error($stmt));
return false;
}
} else {
error_log("prepare failed: ".mysqli_stmt_error($stmt));
return false;
}
References
http://php.net/mysqli.prepare
How can I prevent SQL injection in 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
I have a function to search for records by course name:
<?php
function searchByCourse()
{
if (isset($_POST["course_title"])) {
//Copy to local var
$course_title = $_POST["course_title"];
$stmt = self::$conn->prepare("SELECT student_id, student_name, course_title FROM student_info WHERE course_title = ?");
$stmt->bind_param("s", $course_title);
$result = $stmt->execute();
if ($result === FALSE) {
$stmt->close();
return FALSE;
} else {
$results_array = array();
$stmt->bind_result($student_id, $student_name, $course_title_found);
while ($stmt->fetch()) {
echo "Fetch! \n";
$row = array();
$row["student_id"] = $student_id;
$row["student_name"] = $student_name;
$row["course_title"] = $course_title;
$results_array[] = $row;
}
$stmt->close();
return $results_array;
}
} else {
return FALSE;
}
}
?>
The code seems to execute fine but when I test it using curl for course_title=Computing it should return 3 results. However the echo "Fetch!" is never displayed. It seems to be that there is nothing for it to fetch. It's driving me a little crazy. I've checked all the var names in the database and they match up fine. Any ideas what I could be doing wrong here?
EDIT:
This method is part of my class DbHandler. $conn is a protected static MySqli connection object created in function__contruct().
called like this:
$db = new DbHandler();
$db->searchByCourse();
I have other database functions that work fine for this design pattern. The function is being called correctly. I have also checked the $_POST["course_title"] and that is being passed correctly.