SQL syntax error in php code - php

I am passing value from android using POST and run the query in SQL DB using PHP. I am always getting
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near '' at line 1.
The code is working fine if i pass the values directly insted $_POST[].
I've gone through SO but no questions solved my problem. I tried with mysql_real_escape_string($searchTermBits) also but that doesn't worked.
PHP:
<?php
$username = "xxxx";
$password = "xxxx";
$host = "xxxx";
$database = "xxxx";
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$search = $_POST["deskey"];
$search = explode(" ", $search);
$commonwords = "a,an,and,I,it,is,do,does,for,from,go,how,the,etc,in,on,are";
$commonwords = explode(",", $commonwords);
foreach ($search as $value)
{
if (!in_array($value, $commonwords))
{
$query[] = $value;
}
}
$query = implode(" ", $query);
$searchTerms = explode(" ", $query);
$searchTermBits = array();
foreach ($searchTerms as $term)
{
$term = trim($term);
if (!empty($term))
{
$searchTermBits[] = "description LIKE '%$term%'";
}
}
$myquery = "SELECT * FROM `logins` WHERE " . implode(' OR ', mysql_real_escape_string($searchTermBits)) . "";
$query = mysql_query($myquery);
if (!$query)
{
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++)
{
$data[] = mysql_fetch_assoc($query);
}
echo json_encode($data);
mysql_close($server);
?>
What changes can i make this code to work with $_POST[].

Related

Change PHP mssql to sqlsrv (mssql_fetch_row)

I have this code:
$query="Select SUBJECT,NOTES from CAMPNOTIFICATION
where TYPE LIKE 'message_blackboard' AND VALIDAFTER <= GETDATE() AND (VALIDUNTIL >= GETDATE() OR VALIDUNTIL IS NULL)";
$encode = array();
//$query = strtr($query, array('{$raum}' => $raum));
$query_result = mssql_query($query);
while ($row = mssql_fetch_row($query_result))
{
$encode[] = $row;
$text = $row[1];
$text = str_replace("<br />","\n",$text);
$text = str_replace("<br>","\n",$text);
$text = str_replace("<br/>","\n",$text);
$text = str_replace("<p>","\n",$text);
$text = str_replace("\r","",$text);
$text = strip_tags($text);
$text = str_replace("\n","<br>",$text);
$text = str_replace("<br>\r<br>","",$text);
$text = str_replace("<br><br>","<br>",$text);
echo "<h2>" . $row[0] . "</h2>" . $text . "<br>";
}
I have to change the connections to the sqlsrv model. I managed to do it this way:
$query="Select SUBJECT,NOTES from CAMPNOTIFICATION
where TYPE LIKE 'message_blackboard' AND VALIDAFTER <= GETDATE() AND (VALIDUNTIL >= GETDATE() OR VALIDUNTIL IS NULL)";
//$params = array(SQLSRV_PHPTYPE_*);
$encode = array();
$query_result = sqlsrv_query($connection, $query);
if ($query_result === false){
die(print_r( sqlsrv_errors(), true));
}
while ($row = sqlsrv_fetch_object($query_result))
{
//echo "Contenido de Row ". $row -> NOTES;
$encode[] = $row;
$text = $row -> NOTES;
$text = str_replace("<br />","\n",$text);
$text = str_replace("<br>","\n",$text);
$text = str_replace("<br/>","\n",$text);
$text = str_replace("<p>","\n",$text);
$text = str_replace("\r","",$text);
$text = strip_tags($text);
$text = str_replace("\n","<br>",$text);
$text = str_replace("<br>\r<br>","",$text);
$text = str_replace("<br><br>","<br>",$text);
echo "<h2>" . $row -> SUBJECT . "</h2>" . $text . "<br>";
}
But I need to keep the structure in which I use the position of the array instead of calling the object.
Does anyone know of any way? Thank you very much.
Solution:
Function mssql_fetch_row() is part of the MSSQL PHP extension (mssql_ functions) and fetches one row of data as a numeric array. If you want to get the data in similar way using PHP Driver for SQL Server (sqlsrv_ functions), you should use sqlsrv_fetch_array() with SQLSRV_FETCH_NUMERIC as second parameter value.
Your code should look like this:
<?php
....
while ($row = sqlsrv_fetch_array($query_result, SQLSRV_FETCH_NUMERIC)) {
$encode[] = $row;
// Additional code here ...
}
...
?>
Additional explanations:
If the SELECT statement returns more than one result set, you need to use sqlsrv_next_result() to make the next result of the specified statement active.
Example, using MSSQL extension:
<?php
// Connection
$server = "server\instance";
$database = "database";
$username = "username";
$password = "password";
$conn = mssql_connect($server, $username, $password);
mssql_select_db($database, $conn);
// Statement
$sql = "
SELECT [name], [age] FROM [dbo].[persons];
SELECT [name], [salary] FROM [dbo].[jobs];
";
$stmt = mssql_query($sql, $conn);
// Fetch data
do {
while ($row = mssql_fetch_row($stmt)) {
echo print_r($row, true);
}
} while (mssql_next_result($stmt));
// End
mssql_free_result($stmt);
mssql_close($conn);
?>
Example, using SQLSRV extension:
<?php
// Connection
$server = "server\instance";
$database = "database";
$username = "username";
$password = "password";
$info = array(
"Database" => $database,
"UID" => $username,
"PWD" => $password
);
$conn = sqlsrv_connect($server, $info);
// Statement
$sql = "
SELECT [name], [age] FROM [dbo].[persons];
SELECT [name], [salary] FROM [dbo].[jobs];
";
$stmt = sqlsrv_query($conn, $sql);
// Fetch data
do {
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
echo print_r($row, true);
}
} while (sqlsrv_next_result($stmt));
// End
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn);
?>
Function equivalence:
The table below displays more information about the equivalence between the functions from each extension:
--------------------------------------------------------------------------------------
MSSQL PHP extension PHP Driver for SQL Server
--------------------------------------------------------------------------------------
mssql_fetch_assoc($stmt) sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)
mssql_fetch_row($stmt) sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC)
mssql_fetch_array($stmt, MSSQL_ASSOC) sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)
mssql_fetch_array($stmt, MSSQL_NUM) sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC)
mssql_fetch_array($stmt, MSSQL_BOTH) sqlsrv_fetch_array($stmt, SQLSRV_FETCH_BOTH)
mssql_next_result($stmt) sqlsrv_next_result($stmt)

Have Both And/Where In PHP SQL Statement

I connect to MSSQL server and my query does not return any results - if I use the echo $sql; statement all that I have returned is Array so I can't even check for a syntax issue!
How should this syntax be ammended so that all 3 where statements execute as they should?
<select name="employee" id="employee"></select>
$option = array();
$option['driver'] = 'mssql';
$option['host'] = 'IP ADDRESS';
$option['user'] = 'USER';
$option['password'] = 'Pass';
$option['database'] = 'DB';
$option['prefix'] = '';
$db = JDatabase::getInstance($option);
$query = $db->getQuery(true);
$query->select($db->quotename(array('Red,Blue,Green')));
$query->from($db->quoteName('EMS'));
$datefield_name = $db->quoteName('TermDate');
$employee_name = $db->quoteName('employee');
$query->where("$datefield_name >= " . $db->quote($d1), 'AND');
$query->where("$datefield_name <= " . $db->quote($d2));
if ($employeename != 'All') {
$query->where("$employee_name <= " . $db->quote($employee));
}
$db->setQuery($query);
echo $query;
$query = $db->loadObjectList();
I'm no expert at MSSQL, but my first impression is that in your where-statements you should not include your variables inside the quotes. So instead of
$query->where("$datefield_name <= " . $db->quote($d2));
try
$query->where($datefield_name . " <= " . $db->quote($d2));

Deprecated mysql_query and mysql_connect - code update

Years ago a friend of mine wrote a piece of code for me to do some simple function of recording a learning progress for my joomla site users. Now that I have updated the Joomla to 3.6 on PHP7, the site is reporting deprecated queries which did not surprise me. I tried to replace the queries with mysqli but I have failed to make the function work. Would someone take a look for me? Thank you so much.
<?php
/* $host = "localhost";
$user = "administrator";
$pass = "web-Test";//enter here your sql password
$db_name = "e-learning";
$link = mysql_connect($host, $user,$pass);
mysql_select_db($db_name, $link)or die("unable to select database"); */
include'const.php';
$link = mysql_connect($host, $user,$pass);
if (!$link) {
echo('Could not connect');
}
else {
mysql_select_db($db, $link) or die("can not select database").mysql_error();
}
$ip=getenv('REMOTE_ADDR');
//$new_array_without_nulls = array_filter($_POST, 'strlen');
if($_POST)
{
// --------comment
$uid = $_POST['uid'];
unset($_POST['uid']);
$cmt = array();
foreach($_POST as $key => $value)
{
if ($value != 'true' && $value != 'Progress' && $value != 'false')
{
$cmt[$key] = $value;
}
}
foreach ($cmt as $key => $value)
$cmt_value = implode(',' , $cmt);
// --------Check
$check = array();
foreach($_POST as $key => $value)
{
if ($value == 'true')
{
$check[$key] = $value;
}
}
//finding key
$check_key = array();
foreach ($check as $key => $value){
array_push($check_key,$key);
}
foreach ($check_key as $key => $value)
$check_value = implode(',' , $check_key);
//$uid = $user->get('id');
$content_name = $_POST['contentname'];
function CheckExistContentName($content_name,$uid){
$name_exist = mysql_query("select * from Progress where content_name = '$content_name' and User_id = $uid ");
$arr = array();
while($row = mysql_fetch_array($name_exist))
{
$arr = $row;
}
return $arr;
}
if(CheckExistContentName($content_name,$uid))
{
$sql = "update Progress set User_id = '".$uid."', ip = '".$ip."',content_name = '".$content_name."',arr_check = '".$check_value."',arr_cmt = '".$cmt_value."' where content_name = '$content_name' and User_id = $uid";
$rs_result = mysql_query($sql);
echo "<h2> Your learning progress has been updated </h2>";
}
else
{
$sql = "insert into Progress(User_id,ip,content_name,arr_check,arr_cmt) values ('".$uid."','".$ip."','".$content_name."','".$check_value."','".$cmt_value."')";
$rs_result = mysql_query($sql);
echo "<h2> Your learning progress has been saved </h2>";
}
}
//}
?>
Your friend did it completely wrong in a Joomla sense. He hard coded a MySQL connection (including password) into a file instead of using the Joomla database class.
On top of that he is using unsafe variables directly in his MySQL queries, which means your site is at very high risk of being hacked.
If I was you, I would get a professional to fix this issue properly.

null value when i opened the php script in IE

I am trying to fetch the values from mysql table based on the certain values. below is my php script where i am getting json values from android and then parse it to array the passing array in to the select query.
So, when i open the script in IE i am getting values as null instead of []. What is wrong here.
php
<?php
$username = "xxxxx";
$password = "xxxxxx";
$host = "localhost";
$database="xxxxxx";
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$JSON_received = $_POST["JSON"];
$obj = json_decode($JSON_received,true);
foreach ($obj['ilist'] as $key => $value)
{
//echo "<br>------" . $key . " => " . $value;
$im[] = $value;
}
$myquery = "SELECT * FROM Movies WHERE im_rat IN ('$im')";
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
die;
}
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
echo json_encode($data);
mysql_close($server);
?>
Can anyone help ?

How to use rows of Mysql array in PHP function?

I have a function in PHP and I would like to export an array from my MYSQL Database and then use the rows in a loop to do some stuff with them.
$DB_Server = "XXX.XXX.XXX.XXX";
$DB_Username = "XXXX";
$DB_Password = "XXXXX";
$DB_Database = "XXXXX";
$conn = new mysqli($DB_Server, $DB_Username, $DB_Password, $DB_Database);
$query = "Select Name, Wert from test.DBPBX";
function show(array $options) {
global $showresult, $master, $conn, $query;
$result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($result)) {
$cnlongname = $row["Name"];
$usercontent = $row["Wert"];
$cn = $cnlongname;
$options['config']->value = 1;
$config = $options["config"]->value;
$show = new SimpleXMLElement("<show/>");
$user = $show->addChild("user");
$user->addAttribute("cn", $cn);
if ($config)
$user->addAttribute("config", "true");
print "cmd: " . htmlspecialchars($show->asXML()) . "\n";
$showresult = $master->Admin($show->asXML());
print "result: " . htmlspecialchars($showresult) . "\n";
$mod = "text=".$usercontent;
$modify = new SimpleXMLElement("$showresult");
$user = $modify->user;
$path = explode("/device/hw/", $mod);
$srch = $user;
$nsegments = count($path);
$i = 1;
foreach ($path as $p) {
if ($i == $nsegments) {
// last part, the modification
list($attr, $value) = explode("=", $p);
$srch[$attr] = $value;
} else {
$srch = $srch->$p;
}
$i++;
}
$modify = new SimpleXMLElement("<modify>" . $user->asXML() . "</modify>");
print "cmd: " . htmlspecialchars($cmd = $modify->asXML()) . "\n";
// do it
$result = $master->Admin($cmd);
print "result: " . htmlspecialchars($result);
}
}
For $cn I would like to use $cnlongname (or $row["Name"]). And for $mod I would like to use $usercontent (or $row["Wert"]). However when I would like to use it I get an error after the first loop:
Warning: mysqli_fetch_assoc() expects parameter 1 to be
mysqli_result, string given in /sample.php on
line 175
Line 175 is:
while ($row = mysqli_fetch_assoc($result)) {
Can you please help me?
Inside your while loop you overwrite your result, therefore you lose your mysql result and cannot query it any more.
// do it
$result = $master->Admin($cmd);
Use a different variable there. :)

Categories