How to pass special characters through php from a mssql database - php

I have this code is working fine my application gets the data with json and is all fine but when I insert special characters like ñ which I need to get I can't have been told that I should use the utf8_encode but I just don't know how to apply it here since.
<?php
require_once(dirname(__FILE__).'/ConnectionInfo.php');
//Set up our connection
$connectionInfo = new ConnectionInfo();
$connectionInfo->GetConnection();
if (!$connectionInfo->conn)
{
//Connection failed
echo 'No Connection';
}
else
{
if (isset($_POST['mod']) && isset($_POST['lec']) && isset($_POST['clase']))
{
$mod = $_POST['mod'];
$lec = $_POST['lec'];
$clase = $_POST['clase'];
//Create query to retrieve all contacts
$query = 'SELECT TituloEjercicio,PreguntaEjercicio,Opcion1Ejercicio,Opcion2Ejercicio,Opcion3Ejercicio,Opcion4Ejercicio,EstaCorrectaEjercicio FROM ejercicios WHERE QueModulo = ? and QueLeccion = ? and Queclase = ?';
$params = array($mod,$lec,$clase);
$stmt = sqlsrv_query($connectionInfo->conn, $query,$params);
if (!$stmt)
{
//Query failed
echo 'Query failed';
}
else
{
$contacts = array(); //Create an array to hold all of the contacts
//Query successful, begin putting each contact into an array of contacts
while ($row = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC)) //While there are still contacts
{
//Create an associative array to hold the current contact
//the names must match exactly the property names in the contact class in our C# code.
$contact = array("lbl_variable_cuestionario_titulo" => $row['TituloEjercicio'],
"lbl_variable_pregunta" => $row['PreguntaEjercicio'],
"opcion1" => $row['Opcion1Ejercicio'],
"opcion2" => $row['Opcion2Ejercicio'],
"opcion3" => $row['Opcion3Ejercicio'],
"opcion4" => $row['Opcion4Ejercicio'],
"EstaCorrecta" => $row['EstaCorrectaEjercicio']
);
//Add the contact to the contacts array
array_push($contacts, $contact);
}
//Echo out the contacts array in JSON format
echo json_encode($contacts);
sqlsrv_close($connectionInfo->conn);
}
}
sqlsrv_close($connectionInfo->conn);
}
sqlsrv_close($connectionInfo->conn);
?>

If your issue lies with pushing non-latin characters to MySQL then you might just have to configure your database to use UTF8. There are good tutorials online that show you how to do that.

Related

No data passed using UnityWebRequest POST

I'm trying to retrieve some data from a MySQL database through php POST method to Unity.
But somehow, when I use the UnityWebrequest the post variable is always empty.
My C# script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class IDCheck : MonoBehaviour
{
int onlineID = -1;
readonly string urlCheckIdentifier = "http://www.mywebsite.php";
void Start(){
if (Application.internetReachability != NetworkReachability.NotReachable){
StartCoroutine("GetOnlineID");
}
}
void SetID(int _id){
onlineID = _id;
}
IEnumerator GetOnlineID(){
// TEST NUMBER 2
List<IMultipartFormSection> form = new List<IMultipartFormSection>();
form.Add(new MultipartFormDataSection("onlineid", "test"));
/* THIS WAS ATTEMPT NUMBER 1
WWWForm form = new WWWForm();
form.AddField("onlineid", "test");
*/
UnityWebRequest www = UnityWebRequest.Post(urlCheckIdentifier, form);
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError){
Debug.Log("Error on upload");
} else {
Debug.Log(www.downloadHandler.text);
DownloadData data = JsonUtility.FromJson<DownloadData>(www.downloadHandler.text);
bool idFound = (data.succes == false)?false:true;
if (!idFound){
Debug.Log("Didnt work");
Debug.Log(data.succes);
} else {
SetID(data.id);
Debug.Log(onlineID);
}
}
}
}
My PHP script:
<?php
include_once 'dbconnect.php';
// UNIQUE DEVIDE ID IS GIVEN FROM THE APP VIA POST METHOD
$onlineid = $_POST["onlineid"];
// CHECK IF ID EXISTS IN CURRENT USERS TABLE
$query = "SELECT id, username FROM users WHERE uniqueID='$onlineid'";
$result = mysqli_query($dbconnection, $query);
$row = mysqli_fetch_row($result);
if($row){
// IF ID WAS FOUND, RETURN JSON TO THE APP
$dataArray = array('success' => true, 'error' => '', 'id' => $row[1], 'username' => $row[2], 'TESTuniqueIDPassed' => $onlineid);
} else {
// ID WAS NOT FOUND, CREATING NEW ONE.
$query2 = "INSERT INTO users(uniqueID) VALUES ('$id')";
$result2 = mysqli_query($dbconnection, $query2);
// GETTING THE NEWLY CREATED ID FROM THE DB.
$query3 = "SELECT id, username FROM users WHERE uniqueID='$id'";
$result3 = mysqli_query($dbconnection, $query3);
$row3 = mysqli_fetch_row($result3);
// RETURNING JSON WITH THE NEW ID
$dataArray = array('success' => true, 'error' => '', 'id' => $row3[1], 'username' => $row3[2], 'TESTuniqueIDPassed' => $onlineid);
}
header('Content-Type: application/json');
//echo json_encode($dataArray);
echo $onlineid;
?>
As you can see I even tried to just echo the $onlineid which should be populated with the POST method from unity, but that's always returning an empty string.
I've tried google of course but most posts about this subject are pretty old.
The solution to add
www.chunkedTransfer = false;
in front of the yield return call is now depreciated, and another suggested solution was to put
www.useHttpContinue = false;
in front of the yield return also did nothing to solve the problem.
Anybody any ideas where to go from here?
Regards,
Mark
I've tried a couple of things in the meantime while waiting for an anwser.
Stumbled upon an anwser myself so I will post it for the next person to have the same issue:
Your link should start with https instead of http, because Unity does not allow insecure links anymore.
Using MultipartFormDataSection still wont work, but WWWForm will!

JSON returns [null,null] in my app

I want to send database records with a PHPH file via json to my app I am making with IntelXDK. Because I can't use PHP code with the Intel XDK, I needed to use JSON. I want to show the two records 'quote' and 'author' from my 'quotes' table on my screen. Someone helped me to this code but it just returns [null,null]instead of the two records I need.. I tried debugging but I am new to PHP so I can'get it to work.. Anyone who can help or sees an error in this code? Thanks!
PS: Yes I now there are already multiple questions asked on this subject by other people. I have read them all but none of them solves my question..
<?php
if(isset($_GET["get_rows"]))
{
//checks the format client wants
if($_GET["get_rows"] == "json")
{
$link = mysqli_connect("localhost", "xxxxx", "xxxxx", "xxxx");
/* check connection */
if (mysqli_connect_errno()) {
echo mysqli_connect_error();
header("HTTP/1.0 500 Internal Server Error");
exit();
}
$query = "SELECT quote, author FROM quotes WHERE id = " . date('d');
$jsonData = array();
if ($result = mysqli_query($link, $query)) {
/* fetch associative array */
$row = $result->fetch_assoc($result);
// Create a new array and assign the column values to it
// You can either turn an associative array or basic array
$ret= array();
$ret[] = $row['quote'];
$ret[] = $row['author'];
//encode to JSON format
echo json_encode($ret);
}
else {
echo json_encode($ret);
}
/* close connection */
mysqli_close($link);
}
else
{
header("HTTP/1.0 404 Not Found");
}
}
else
{
header("HTTP/1.0 404 Not Found");
}
?>
You have a bug in fetch_assoc() function call - remove $result parameter. If you had error reporting enabling, you should see:
Warning: mysqli_result::fetch_assoc() expects exactly 0 parameters, 1 given
Just change it to:
$row = $result->fetch_assoc();
In javascript to parse this response, just do this:
var obj = JSON.parse(xmlhttp.responseText);
document.getElementById("quote").innerHTML = obj[0];
document.getElementById("author").innerHTML = obj[1];
I think your problem is with fetch_assoc()
Try to use that :
$row = mysqli_fetch_assoc($result);
instead of
$row = $result->fetch_assoc($result);
It's works for me with your example
change this
$row = $result->fetch_assoc($result);
to
$row = $result->fetch_assoc();
Just change it to:
$row = $result->fetch_assoc();
Updated:
response = JSON.parse(xmlhttp.responseText);
you can now access them independently as:
reponse.quote and response.author

json_encode doesn't get echo'ed

I'm trying to pull some records from the DB with the code below, but my echo json_encode($contacts); at the end of the code doesn't print anything. Nor does any echo put right above that.
<?php
require_once(dirname(__FILE__).'/ConnectionInfo.php');
//Set up our connection
$connectionInfo = new ConnectionInfo();
$connectionInfo->GetConnection();
if (!$connectionInfo->conn)
{
//Connection failed
echo 'No Connection';
}
else
{
//Create query to retrieve all contacts
$query = 'SELECT Numero_Leccion,Titulo_Leccion,Ejemplo_Leccion FROM leccion';
$stmt = sqlsrv_query($connectionInfo->conn, $query);
if (!$stmt)
{
//Query failed
echo 'Query failed';
}
else
{
$contacts = array(); //Create an array to hold all of the contacts
//Query successful, begin putting each contact into an array of contacts
while ($row = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC)) //While there are still contacts
{
//Create an associative array to hold the current contact
//the names must match exactly the property names in the contact class in our C# code.
$contact = array("Numero_Leccion"=>$row['Numero_Leccion'],"Titulo_Leccion"=>$row['Titulo_Leccion'],"Ejemplo_Leccion"=>$row['Ejemplo_Leccion']);
//Add the contact to the contacts array
array_push($contacts, $contact);
}
//Echo out the contacts array in JSON format
echo json_encode($contacts);
}
}
?>
Put error_reporting(E_ALL & ~E_NOTICE); ini_set('display_errors', '1'); somewhere on top of your script and see if there are any errors
(taken from Why echoing JSON encoded arrays won't produce any output)
Try this:
while ($row = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC))
{
$contacts[] = array("Numero_Leccion"=>$row['Numero_Leccion'],"Titulo_Leccion"=>$row['Titulo_Leccion'],"Ejemplo_Leccion"=>$row['Ejemplo_Leccion']);
}
header('Content-Type: application/json');
echo json_encode($contacts);

How to make echo results in table hyperlinks

I have retrieved data from DB and inserted into a html table however I want to make each value in the table a hyperlink to another page. Below I have tried making the pupil_id and link to a profile.php but all pupil_id values have now vanished!
(if (!isset($_POST['search'])) {
$pupils = mysql_query("SELECT * FROM pupil") or die("Cant find Pupils");
$count = mysql_num_rows($pupils);
if ($count == 0) {
$totalpupil = "There are currently no Pupils in the system.";
} else {
while ($row = mysql_fetch_array($pupils)) {
?>
<tr>
<td><?php echo '<a href="profile.php?id=' .$row['pupil_id'] . '"</a>' ?></td>
<td><?php echo $row['pupil_name'] ?></td>
<td><?php echo $row['class_id'] ?></td>
</tr>
<?php
}
}
})
The finishing table should display every hyperlink as a hyperlink to another page. Any help?
Because your HTML is invalid, you are missing a closing > and you have no text defined for the hyperlink
<?php echo '<a href="profile.php?id=' .$row['pupil_id'] . '"</a>' ?> //Wrong
Correct would be
<?php echo ''.$row['pupil_id'].''; ?>
Try replace this:
<?php echo '<a href="profile.php?id=' .$row['pupil_id'] . '"</a>' ?>
with this:
<?php echo "<a href='profile.php?id=".$row['pupil_id']."'>link</a>"; ?>
Also, you dont have <table> tags at all.
You don't put any text between your link tags, text here
Maybe this will help you:
<td><?php echo ''.$row['pupil_name'].'' ?></td>
http://uk3.php.net/mysql_query
Watch out, which ever resource you are learning from may well be quite old. mysql_query is now deprecated.
http://uk3.php.net/manual/en/ref.pdo-mysql.php is a replacement.
Here is a kick starter to using PDO (this is much much safer) i write a while ago.
Include this file in which ever php script needs to access your db. An example file name would be 'database.php' but that is your call. Set the namespace from 'yourproject' to whatever your project is called. Correct the database credentials to suit your database
This will save you a lot of headaches hopefully!
I have given some example uses at the bottom for you. I remember when i started out getting clear advice was sometimes hard to come by.
//***** in a database class file*****/
namespace yourproject;
class Database {
private $db_con = '';
/*** Function to login to the database ***/
public function db_login()
{
// Try to connect
try{
// YOUR LOGIN DETAILS:
$db_hostname = 'localhost';
$db_database = 'yourdatabasename';
$db_username = 'yourdatabaseusername';
$db_password = 'yourdatabasepassword';
// Connect to the server and select database
$this->db_con = new \PDO("mysql:host=$db_hostname;dbname=$db_database",
"$db_username",
"$db_password",
array(\PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
// Prevent emulation of prepared statements for security
$this->db_con->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
$this->db_con->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
return true;
}
// If it fails, send user to maintenance page
catch(PDOException $e)
{
header("location:http://yourwebsiteurl.com/maintenance.php");
exit();
}
}
/*** Function for database control ***/
public function db_control($query , $parameters, $returnID = false)
{
if(!is_array($query) && is_array($parameters))
{
try{
//prepare the statement
$statement = $this->db_con->prepare($query);
//execute the statement
$statement->execute($parameters);
//check whether this is a select, if it is then we need to retrieve the selected data
if(strpos($query, 'SELECT') !== false)
{
//fetch the results
$result = array();
while( $row = $statement->fetch(\PDO::FETCH_ASSOC) )
{
$result[] = $row;
}
//count the results
$count = count($result);
//return the array
return array( 'results' => $result, 'result_count' => $count );
}
//else return the number of affected rows
else{
//count the affected rows and place into a returnable array
$affected_rows = $statement->rowCount();
$returnArray = array('result_count' => $affected_rows);
//check to see if we are to return a newly inserted autoincrement ID from an INSERT
if($returnID)
{
//find the newly created ID and add this data to the return array
$insertID = $this->db_con->lastInsertId();
$returnArray['ID'] = $insertID;
}
return $returnArray;
}
}
catch(PDOException $e)
{
return false;
}
}
else{
return false;
}
}
}
// Start the database class and connect to the database then create a globally accessible function for ease of reference
$db = new \yourproject\Database();
$db->db_login();
function _db( $sql , $params , $returnID = false ){
return $GLOBALS['db']->db_control( $sql , $params , $returnID );
}
When you include this file you now have a new function: _db(). As the function is global it can be called from within any class or std file. When called into a variable as demonstrated below will result in an array like this:
array(
'result_count' => 3,
'results' => array(
array(/*row 1*/),
array(/*row 2*/),
array(/*row 3*/),
.. etc etc
)
)
Now include your database file in your php script:
//call in the database file
require_once 'database.php';
//your query as in the op
$sql = 'SELECT * FROM pupil';
//your params for the query
$params = array();
//running the query and getting the results returned into a variable called $query
$query = _db($sql,$params);
//if no results
if( $query['result_count'] == 0 )
{
echo 'sorry no pupils in the system';
}
else
{
//looping through each result and printing into a html table row
for( $i = 0 ; $i < $query['result_count'] ; ++$i )
{
echo '<tr><td><a href="profile.php?id=' . $query['results'][$i]['pupil_id'] . '"</a></td>';
echo '<td>'. $query['results'][$i]['pupil_name'] . '</td>';
echo '<td>'. $query['results'][$i]['class_id'] . '</td></tr>';
}
}
Your original query but with some parameters passed through
//Passing parameters to the query
//your query
$sql = 'SELECT * FROM pupil WHERE pupil_id = :pupil_id AND class_id = :class_id';
//your params for the query
$params = array(
':pupil_id' => 12,
':class_id' => 17,
);
//running the query and getting the results returned into a variable called $query
$query = _db($sql,$params);
//deal with the results as normal...
If you set the 3rd param as true you can return the automatic id of the row just entered eg:
//where $sql is a query that will INSERT a row
$query = _db($sql,$params, true);

PHP get data from jquery

Im trying to write a simple prgram that the server can get data from client.
I write a simple code in my script
var str = "testString";
$.post("http://anonymous.comze.com/test1.php", { string: str });
in the server,
$var = $_POST['string']; // this fetches your post action
$sql2 = "INSERT INTO afb_comments VALUES ('3',$var)";
$result2= mysql_query($sql2,$conn);
The question is var is always null. The sql2 can be executed if I change $var into "1111" for example,
but if I put $var, it doesn't work. Can anyone give some advice?
your are passing string to the query so it should be
$var = $_POST['string']; // this fetches your post action
$sql2 = "INSERT INTO afb_comments VALUES ('3','".$var."')";
$result2= mysql_query($sql2,$conn);
please also check datatype of the that column.
Use this example and learn from this code how to get data
Or
use can also use this link:
http://api.jquery.com/jQuery.get/
$user and $pass should be set to your MySql User's username and password.
I'd use something like this:
JS
success: function(data){
if(data.status === 1){
sr = data.rows;
}else{
// db query failed, use data.message to get error message
}
}
PHP:
<?php
$host = "localhost";
$user = "username";
$pass = "password";
$databaseName = "movedb";
$tableName = "part parameters";
$con = mysql_pconnect($host, $user, $pass);
$dbs = mysql_select_db($databaseName, $con);
//get the parameter from URL
$pid = $_GET["pid"];
if(empty($pid)){
echo json_encode(array('status' => 0, 'message' => 'PID invalid.'));
} else{
if (!$dbs){
echo json_encode(array('status' => 0, 'message' => 'Couldn\'t connect to the db'));
}
else{
//connection successful
$sql = "SELECT `Processing Rate (ppm)` FROM `part parameters` WHERE `Part Number` LIKE `" . mysqli_real_escape_string($pid) . "`"; //sql string command
$result = mysql_query($sql) or die(mysql_error());//execute SQL string command
if(mysql_num_rows($result) > 0){
$rows = mysql_fetch_row($result);
echo json_encode(array('status' => 1, 'rows' => $rows["Processing Rate (ppm)"]);
}else{
echo json_encode(array('status' => 0, 'message' => 'Couldn\'t find processing rate for the give PID.'));
}
}
}
?>
As another user said, you should try renaming your database fields without spaces so part parameters => part_parameters, Part Number => part_number.

Categories