This question already has answers here:
json_encode() escaping forward slashes
(4 answers)
Closed 6 years ago.
I am trying to get html in a PHP array. When I print the variable out the table is in the correct format but be it is outputted to the array there are added backslashes to my html closing tags (Example: </th>). I didnt think there needed to be any escape characters for slash in PHP. When I print_r($table); it outputs without adding the backslash and outputs the table correctly in my browser but when I add the html table to a PHP array and then output the array as a JSON object it adds the backslash to my html closing tag as shown in the output below from my browser. Any thoughts would be helpful.
Output:
{"data":{"success":"true","carriers":"1,2","table":"
CarrierId<\/th>
CarrierName<\/th>
1<\/td> UHC<\/td><\/tr>
2<\/td> BlueCross<\/td><\/tr><\/table>"}}
PHP:
<?php
// Show all information, defaults to INFO_ALL
//phpinfo();
/*environment:
OS: windows Server 2012 Standard build 9200
IIS: IIS version 8.0.9200.16384 --> Authentication - win auth ->enabled, Anonymou auth -->disabled, CGI -> Impersonate User = true
http://www.microsoft.com/web/downloads/platform.aspx
http://blogs.msdn.com/b/brian_swan/archive/2010/02/10/sql-server-driver-for-php-understanding-windows-authentication.aspx
SQL: - MS SQL server 10.5.1600
PHP: PHP version 5.4.26 for IIS, copy php_sqlsrv_54_ts.dll to C:\Program Files (x86)\PHP\v5.4\ext directroy from
http://www.iis.net/learn/application-frameworks/install-and-configure-php-on-iis/install-the-sql-server-driver-for-php
php.ini file add
extension=php_pdo_sqlsrv_54_ts.dll
extension=php_sqlsrv_54_ts.dll
*/
//Connect to SQL with Authentication
$serverName = "PFIT-00-lync-03"; //serverName\instanceName
$connectionInfo = array( "Database"=>"spicewebinsurance", "UID"=>"spicerest", "PWD"=>"Password1");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn ) {
//echo "Connection established.<br />";
}else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
$tsql= "select convert(varchar,CarrierId) as CarrierId, CarrierName as CarrierName from dbo.Carrier ";
//print_r($tsql) ;
$stmt=sqlsrv_query($conn, $tsql);
$table = "<table> <th>CarrierId</th><th>CarrierName</th>";
// Create table body
if ($stmt) {
$rows = sqlsrv_has_rows( $stmt );
if ($rows === true)
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) )
{
$carriers[] = $row['CarrierId'];
$table .= "<tr><td>";
$table .= $row['CarrierId'];
$table .= "</td><td>";
$table .= $row['CarrierName'];
$table .= "</td></tr>";
}
$table .= "</table>";
$carriers=implode(',', $carriers);
$return=array(
"success"=>"true",
"carriers"=>$carriers,
"table"=>$table
);
}
else
{
$return['success']=false;
}
echo '{"data":'.json_encode($return).'}';
sqlsrv_free_stmt( $stmt);
?>
I haven't read up on why the / is escaped but use option JSON_UNESCAPED_SLASHES:
echo '{"data":'.json_encode($return, JSON_UNESCAPED_SLASHES).'}';
Related
I have an issue where using sqlsrv_fetch_array is returning NULL. I am trying to do a simple query on a view in MS SQL that I have verified in SQL Server Management Studio provides results.
I am running PHP 7.4.4 on Windows Server 2016 x64, with version 5.8 of the PHP SQL drivers and 17.5.2.1 of the ODBC driver.
Similar queries are being run on 4 other views within this database and all work fine. Below is the code I'm testing:
<?php
include("../mscon.php");
$msConnInfo = array( "Database"=>"XYZ", "UID"=>"username", "PWD"=>"password");
$msConn = sqlsrv_connect( $msServerName, $msConnInfo);
if($msConn)
{
//echo "Connection established.\n";
}
else
{
//echo "Connection could not be established.\n";
die( print_r( sqlsrv_errors(), true));
}
$query = "SELECT * FROM Public_Web";
$result = sqlsrv_query($msConn, $query, array(), array( "Scrollable" => 'static' )) or die( print_r( sqlsrv_errors(), true));
if ($result === false) {
die(print_r(sqlsrv_errors(), true));
}
else
echo "We good fam, no errors<br/>\n";
var_dump($result);
if(sqlsrv_has_rows($result))
{
echo "<br/>Rows exist<br/>\n";
$numRows = sqlsrv_num_rows($result);
echo "There are $numRows rows<br/>\n";
while ($row = sqlsrv_fetch_array($result));
{
var_dump($row);
}
}
else
{
echo "no results were found<br/>\n";
}
sqlsrv_free_stmt( $result);
sqlsrv_close($msConn);
?>
The above code outputs lets me know that there are no errors and that 1493 rows exist in the view. But when I do a var_dump on $row it outputs NULL. All of the fields in the view I'm trying to access are varchar and there are only 7 fields total.
I have tried just grabbing one field in my query instead of all fields, no change in results. It seems like I have tried all possible troubleshooting methods.
Anything you can think of would be greatly appreciated. Thanks.
Problem solved. We ended up deleting the view in SQL and recreating it. No idea why it wasn't working properly.
Hello i am seen lot of question like Session doesn't working first time. But couldn't see any good explanation on this question and why doesn't working first time also what is happening during sessioning. Mine is also like others first time doesn't working after that works fine.
this is php which is sessioning.
session_start();
$PersonName=$_GET['PersonName'];
$SurName=$_GET['SurName'];
$TestXML=$_GET['TestXML'];
$TestDate=$_GET['TestDate'];
$TestPkID='0000000000000000000000000000';
include('DBConnect.php');
$proc = "{call p_set_Test(?,?,?,?,?,?,?,?,?)}";
$params = array(array($TestDate,SQLSRV_PARAM_IN),
array(0,SQLSRV_PARAM_IN),
array($PersonName,SQLSRV_PARAM_IN),
array($SurName,SQLSRV_PARAM_IN),
array($TestXML,SQLSRV_PARAM_IN),
array('',SQLSRV_PARAM_IN),
array(101,SQLSRV_PARAM_IN),
array(10,SQLSRV_PARAM_IN),
array($TestPkID, SQLSRV_PARAM_OUT)
);
$result = sqlsrv_query( $conn, $proc, $params);
if( $result === false )
{
echo "Error in executing statement 3.\n";
die( print_r( sqlsrv_errors(), true));
$message2 = "aldaatai";
echo "<script type='text/javascript'>alert('$message2 ' + $TestPkID);</script>";
}
$_SESSION['idpktestsession'] = $_POST["idpktest"] = $TestPkID;
$_SESSION['persontestname'] =$_POST['persontrollname'] = $PersonName;
$_SESSION['persontestlastname'] =$_POST['persontrolllastname'] = $SurName;
this is getting value from sessioned values
<?php include('DBConnect.php');
session_start();
$diskuserid = $_SESSION['idpktestsession'];
$diskusername = $_SESSION['persontestname'];
$diskuserlastname = $_SESSION['persontestlastname'];
$diskuserlastname = mb_substr($diskuserlastname, 0, 1);
?>
<?php
$proc = "{call p_rpt_Pattern(?,?)}";
$params = array($diskuserid,'M');
$procarr = array();
$result = sqlsrv_query( $conn, $proc, $params);
while ($row = sqlsrv_fetch_array($result))
{?>
<tr>
<td><?php echo $row['PatternCode']?></td>
<td><i class="fa fa-chevron-right rightarrow" > </i></td>
<td><?php echo $row['PatternDesc']?></td>
</tr>
<?php
}
?>
This statement was written incorrect:
$_SESSION['idpktestsession'] = $_POST['idpktest'] = $TestPkID;
If you want to assign the value you can rewrite above statement like this
$_SESSION['idpktestsession'] = $_POST['idpktest'];
and if you want to concatenate two values you can rewrite like this
$_SESSION['idpktestsession'] = $_POST['idpktest'] . ','. $TestPkID;
As long this is question wasn't answered i found why it don't work first time.
Everytime it sending session to another php with value ,its sending with value after page load so if you some how face this error just assign value before page load or put middle loading php insteand of showing direct.
It's not a duplicate question about UTF-8 Unicode.
I am new to php and I am trying to create a json response.
I added data into my database properly as follows.
Then I tried to connect to DB and i did it successfully .
but after that when I tried to create a json response by using the following code, it doesn't shows any json response .
My PHP code is :
<?php
define('HOST','localhost');
define('USER','root');
define('PASS','qwerty');
define('DB','carol');
$con = mysqli_connect(HOST,USER,PASS,DB);
if (!$con)
{
echo "Please try later..";
}
else
{
echo "DB Connected..";
}
$sql = "SELECT * from songs";
$res = mysqli_query($con,$sql);
if (!$res)
{
echo "query failed..";
}
else
{
echo "Query success..";
echo (mysqli_num_rows($res));
}
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array('title'=>$row[0]),
array('url'=>$row[1]),
array('lyrics'=>$row[2])
);
}
echo json_encode(array("result"=>$result));
mysqli_close($con);
?>
I'm getting only echo of DB Connected , Query Success and 14 (no of rows)
I'm trying PHP for the first time by using some online tutuorials.
if I did any mistake in my code,please help me to find my mistake.
Thank you in advance.
After I added echo var_dump($res);
I got
This question already has answers here:
Get number of rows in SQL-Server with PHP
(2 answers)
Closed 9 years ago.
I know there have been lots of questions about this but I need some specific help, I'm new to sql and php, so sorry for bad coding and poor indenting. What I am trying to do is count the number of rows to a specific column then when I find out how many have this id from this column then I would like it to send this number back to the php page. ATM I am using a like query I don't want this effected.
My layout is 3 pages the index the part choices and the part location, the user inputs a part number into the index page which is then searched against the database which then displays the parts that match or are like the users input on the part choices page. then you click on the part you want and then it takes you to the locations page and showing the closest locations for this part.
What I am trying to do is when the user puts in the part number a query runs and searches the database counting the number of rows that have or are like the input, then outputs the parts like it usually does, but what i want to happen is if there is only one row with that part number i want it to say row = 1 so i can then run an if statement using this value. i have looked into different code and cant quiet find what I'm looking for these are the examples I have found and have tryied to modify for what I need. but i have had no luck.
$query = "SELECT (column) FROM table WHERE column = value";
2.$results = mysql_query($query);
3.$rows = mysql_num_rows($results);
4.echo $rows ;
seperate code below
<?php
$serverName = "serverName\instanceName";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo );
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT FirstName, LastName FROM SomeTable";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
echo $row['LastName'].", ".$row['FirstName']."<br />";
}
sqlsrv_free_stmt( $stmt);
?>
i would like the code or query to be within the php that i have, any ideas would be great or examples sorry about poor english many thanks
my code for my page is below:
<!DOCTYPE html>
<head>
<meta name="viewport" content="width=device-width, user-scalable=false;">
<script type="text/javascript">
function submit()
{
document.getElementById("start").click(); // Simulates button click
document.submitForm.submit(); // Submits the form without the button
}
</script>
</head>
<body>
<?php
try {
$serverName = "188.64.188.89";
$connectionInfo = array( "Database"=>"tdStoreLocator", "UID"=>"odbcAdmin", "PWD"=>"Midnight1Midnight1");
$conn = sqlsrv_connect( $serverName, $connectionInfo );
if( $conn === false )
{
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT TOP 10 [company]
,[partnum]
,[description]
FROM [tdStoreLocator].[odbcadmin].[Part]
WHERE Part.partnum LIKE ? or Part.description LIKE ?";
/* Set parameter values. */
$params = array( "%" . str_replace(" ","%",$_POST["part"] ). "%", "%" . str_replace(" ","%",$_POST["part"] ) . "%");
$i = 0;
$x = true;
/*echo print_r($params, true);*/
$stmt = sqlsrv_query( $conn, $sql, $params );
if( $stmt === false)
{
die( print_r( sqlsrv_errors(), true) );
}
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC))
{
if($x == true)
{
echo"<form id=\"submitForm\" action=\"locations.php\" method=\"post\">";
echo"<input type=\"hidden\" name=\"part\" id=\"3\" value=\"".$row['partnum']."\">";
echo"<input type=\"hidden\" name=\"lon1\" id=\"1\" value=\"".$_POST["lon1"]."\">";
echo"<input type=\"hidden\" name=\"lat1\" id=\"2\" value=\"".$_POST["lat1"]."\">";
echo"<button id=\"start\" type=\"submit\">";
echo "<div style=\"font-family:verdana;font-weight:bold;color:#3083FF;font-size:20px;width:100%;text-align:center;margin:0; padding:0;\">";
echo $row['partnum']."<br/>";
echo "</div>";
echo"<img style=\"width:50%;\"; src=\"productimages/".$row['partnum'].".jpg\" alt=\"Save icon\" onError=\"this.src='productimages/noimage.jpg'\"/>";
echo "<div style=\"font-family:verdana;color:#3083FF;font-size:20px;width:100%;text-align:center;margin:0; padding:0;\">";
echo $row['description'];
echo "</div>";
echo"</button>";
echo"</form>";
}
$i++;
}
sqlsrv_free_stmt( $stmt);
}
catch (Exception $e)
{
echo 'Caught exception: ', $e->getMessage(), "\n";
}
if($i < 1)
{
echo "<div style=\"font-family:verdana;font-weight:bold;color:#3083FF;font-size:20px;width:100%;text-align:center;\">";
echo "No results found, Please check your spelling of the part number or description.";
echo "</div>";
}
if($i == 1 ) {
echo"<img onload=\"setTimeout(submit(),00001);\" src=\"index.jpg\" onError=\"this.src='productimages/noimage.jpg'\"/>";
}
?>
</body>
</html>
Instead you can use count in query.
$query = "SELECT count(column) FROM table WHERE column = value";
following step count search value in mysql table.
$query = "SELECT * FROM table WHERE fieldName = fieldvalue";
$results = mysql_query($query);
$rows = mysql_num_rows($results);
echo $rows ;
all,
i have been lurking on stackoverflow for a few years now, always able to find the help needed to resolve the issue at hand. however, this time, i needed to create my first question as i was unable to find questions that hit on the same issue i am encountering.
i have been stumped for over a week and am getting into hot water at work because i already blew my estimated date. i put myself at your mercy in the hopes that you may help me with my coding headache.
i am able to return data from executing a stored procedure through PHP on a SQL 2008 server on a VM (running windows 2008 r2) where i pass in one parameter.
that parameter has a total of eleven (11) choices. whenever i pass in one (1) of those choices, expected data is returned.
however, whenever i use any of the other choices, no data is returned (and with my current code, no errors are returned either).
there are 11 choices of $application_selected to pass into the stored procedure and only one (1) of those choices returns data. none of the others return data or errors.
here is my entire code:
<!DOCTYPE html>
<html>
<head>
<title>data</title>
</head>
<body>
<?php
////////////////////////////////////////////////////////////////////////////
//connection information
$servername = "192.168.1.104";
$username = "sa";
$password = "*";
$database = "*";
$connection_info = array( "Database"=>$database, "UID"=>$username, "PWD"=>$password);
$conn = sqlsrv_connect( $servername, $connection_info);
if($conn===FALSE) die( print_r( sqlsrv_errors(), true));
else echo "<font color=\"blue\">DB Connected.</font><br>";
/////////////////////////////////////////////////////////////////////////////
$application_selected = "param1";
$sql_cmd = "EXECUTE GetApprover '$application_selected'";
$execute_this = sqlsrv_prepare($conn, $sql_cmd);
$application_proc = sqlsrv_execute($execute_this);
if($application_proc===FALSE) die( print_r( sqlsrv_errors(), true)); //execute failed; die and display errors
else echo "<font color=\"blue\">DB data retrieved.</font><br><br>";
$row_apps = "";
$count = 0;
echo "<font color=\"blue\">Attempting data output via loop</font><br><br>";
/////////////////////////////////////////////////////////////////////////////
// output data
//echo var_dump($execute_this)."<br><br>";
echo "<font color=\"blue\">Application selected = </font>\"".$application_selected."<font color=\"blue\">\" - data pulled ▼</font><br><br>";
while(($row_apps = sqlsrv_fetch_array($execute_this)) && (sqlsrv_fetch_array($execute_this) <> FALSE)) { //while var has data
if (!isset($row_apps)) die( print_r( sqlsrv_errors(), true));
$count += 1;
echo $row_apps['ApplicationName']." - ".$row_apps['ApproverCode']." - ".$row_apps['ApproverDesc']." - ".$row_apps['FullName']." - ".$row_apps['Email']." - ".$row_apps['UserId']."<br>";
}
/////////////////////////////////////////////////////////////////////////////////
echo "<br><font color=\"blue\">▲ Data displayed.";
echo "<br><br><font color=\"blue\">There were [<font color=\"red\"><b>$count</b></font>] rows returned.<br><br><br>";
echo "<br>\$servername = ";
echo var_dump($servername)."<br>";
echo "<br>\$username = ";
echo var_dump($username)."<br>";
echo "<br>\$password = ";
echo var_dump($password)."<br>";
echo "<br>\$database = ";
echo var_dump($database)."<br>";
echo "<br>\$connection_info = ";
echo var_dump($connection_info)."<br>";
echo "<br>\$conn = ";
echo var_dump($conn)."<br>";
echo "<br>\$application_selected = ";
echo var_dump($application_selected)."<br>";
echo "<br>\$sql_cmd = ";
echo var_dump($sql_cmd)."<br>";
echo "<br>\$execute_this = ";
echo var_dump($execute_this)."<br>";
echo "<br>\$application_proc = ";
echo var_dump($application_proc)."<br>";
echo "<br>\$row_apps = ";
echo var_dump($row_apps)."<br>";
echo "<br>\$count = ";
echo var_dump($count)."<br>";
echo "<br><br><br>";
sqlsrv_close($conn);
echo "<br>DB Connection closed.</font><br><br><br>";
?>
</body>
</html>
it seems my preliminary suspicions (although i had no tangible proof of such) of some sort of db issue was the culprit after pushing my dba (also my director) with some test results from added debug code [like var_dump()/print_r()]. his reply to the issue that caused it all was as follows:
"i don't know what happened but i copied the table content from my dev environment to your dev environment and now things work."
i'm sorry to trouble you all with my issue. i am grateful that Marc B and Raad answered my plea for help so quickly and i really hope this question helps someone in the future.