Overcoming PHP/SQL Server encoding inconsistency - php

Following this blog post, I managed to connect to a MSSQL Server form PHP/CentOS machine. I can get result, however I can not use comparison in the where clause. I should be due to different encoding. Here is my code:
$db = new PDO("odbc:USERS", "username", "password");
$sql = "SELECT top 1 name FROM user where name='تست'";
$stmt = $db->prepare($sql);
$result = $stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
var_dump($row);
Also using $name = mb_convert_encoding('تست', 'utf16'); (also 'UCS-2LE' encoding) Was not helpful. How config PHP/MSSQL to use a single encoding?

Related

Connection is made to the database with php script but no values are returned

I have a successful connection to the database through this php script but it is not returning any values even though it is connected. I am checking for the results on my web browser and it just returns a blank screen. I have used the same script (different queries) to access two other tables in the database and they are both working fine. Here is my code:
<?php
$username = "xx";
$password = "xxx";
$host = "xxxxx";
$database="xxxxx";
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$myquery = "SELECT `AUTHOR`, `In_order` from `authors`";
$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);
?>
It is probably some silly mistake that I have over looked but I have been stuck on it for longer than I should! thanks in advance for any feedback
Tried you code locally on some data and it returns everything ok.
I needed to change the select to match my data
So I am 95% sure the problem is in your query / db settings.
I would first check if your columns in database is really called AUTHOR and 'In_order' with the exact capital letters.
MySql names can be case sensitive depending on your db server settings, and this could be the problem
Sidenote: if you can research mysqli and pdo for connecting to DB instead of mysql that is deprecated.
Try this:
$myquery = "SELECT `AUTHOR`, `In_order` from `authors`";
$query = mysql_query($myquery);
$num = mysql_num_rows($query);
var_dump($query);
var_dump($num);
echo mysql_error();
and tell us what it all says.
Edit: okay, so it's 231 rows in your table, as the var_dump($num) says. Now let's try and get them at last, but in a slightly more efficient way:
while ($row = mysql_fetch_assoc($query)) {
$data[] = $row;
}
echo json_encode($data);
I have a feeling that your "for" loop and mysql_fetch_assoc() inside is what plays tricks with you, because both of them use different internal counters.

Issues with php connection to mySQL database

Hy everyone, I can't wrap my head around this. I'm trying to get some data from a table using PDO. this is my code:
//in db.php I have the connection:
$host = 'localhost';
$db = 'APL';
$dbuser = '';
$pass = ' ';
try{
$conn = new PDO("mysql:host=$host;dbname=$db", $dbuser, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
//in my file I have this:
$id = $_GET['id'];
$sel_sql = "SELECT * FROM users WHERE id =:id";
$stmt = $conn ->prepare($sel_sql);
$stmt -> bindParam(':id', $id);
$stmt -> execute();
$result = $stmt -> fetchAll(PDO::FETCH_ASSOC);
The problem is that print_r($result) returns '1' (just the value 1, therefore I can't access any data stored in the table) as long as $_SESSION['user'] is set.
The whole data-retrieving worked just fine if the $_SESSION['user'] is not set.
Can someone please explain why this is happening? (I'm fairly new to all this and I'm really trying to understand why some issues occur).
Thank you!
The fetchAll function should be returning either an array, or a boolean FALSE.
You report that print_r($result) is displaying an integer value of 1.
I don't see how that's possible, unless you are assigning a different value to $result. Try relocating print_r($result) to immediately follow the assignment from fetchAll.
(My suspicion is that $result is being assigned a value of 1 elsewhere in your code, before you do the print_r. If there were "Issues with php connection to MySQL database", we'd be expecting to see a PDO error of some sort.)
NOTE: I don't think PDO::FETCH_ASSOC is a defined fetch style for the fetchAll function. (fetchAll has different fetch styles than fetch.)
Just in case someone else stumbles upon this, between the $result variable and the print_r($result) I had an include_once(); statement (which was wrongly put there in the first place).
Thank you everyone for your answers.

Insert LaTeX code into MySQL

I am using PHP and MySql. TeX is posted to server.php file through a form and exploded into an array:
foreach($_POST['ques'] as $i){
$arr = explode('~', $i);
}
$sql = "INSERT INTO `QUESTIONS`(`Text`) VALUES ('$arr[2]')";
$run = mysql_query( $sql, $conn ) or die(mysql_error());
Btw echo $arr[2]; shows correct Tex syntax : "[\Rightarrow{z=\frac{43}{-44}}]"
But on database it is stored without backslashes "[Rightarrow{z=frac{43}{-44}}]"
Do not use old mysql_* functions. Use mysqli_*. or PDO as in this example.
The parameterized/prepared query makes you to stop worrying about quoting and malicious sql-attacks. (But drive safely anyway)
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$dbh = new PDO($dsn, $user, $password);
$sth = $dbh->prepare("INSERT INTO `QUESTIONS`(`Text`) VALUES (?)");
$sth->execute(array($arr[2]));

PHP call to SQL server stored procedure doesn't work when ported from Windows to Linux

This is pretty similar to this question, but I need to capture output. It seems to be basically an issue with getting the correct syntax, but using the syntax suggested in the answer didn't work for me.
I have a php application that calls a stored procedure on a SQL Server database which I developed on my Windows laptop running xampp.
My stored procedure looks like this:
CREATE Procedure [dbo].[check_for_barcode] #Sample_Id nvarchar(20), #Barcode_In_table int OUTPUT
AS
SELECT #Barcode_In_table = count(*) FROM dbo.sample_info
WHERE sample_name = #Sample_Id
RETURN #Barcode_In_table
GO
The php code that works on Windows xampp looks like this:
// use a sample Id known to be present in database
$sample_yes = '11335577';
// use a sample Id known NOT to be in database
$sample_no = '0011223344';
$host = 'hostIP';
$db = 'db';
$user = 'user';
$password = 'pw';
try {
$conn = new PDO("sqlsrv:Server=$host;Database=$db", $user, $password);
$sql = "{CALL dbo.check_for_barcode(#Sample_Id=:barcode, #Barcode_In_table=:isInDatabase)}";
$stmt = $conn->prepare($sql);
$stmt-> bindParam('barcode', $sample_yes, PDO::PARAM_STR);
$stmt->bindParam('isInDatabase', $isInDatabase, PDO::PARAM_INT|PDO::PARAM_INPUT_OUTPUT, 4);
$stmt->execute();
echo 'for sample id 11335577 $isInDatabase = '.$isInDatabase."\n";
$stmt-> bindParam(':barcode', $sample_no);
$stmt->execute();
echo 'for sample id 0011223344 $isInDatabase = '.$isInDatabase;
$stmt->closeCursor();
}
catch (Exception $e) {
echo $e->getMessage();
}
The output is:
for sample id 11335577 $isInDatabase = 1
for sample id 0011223344 $isInDatabase = 0
Since moving it to the Linux (Ubuntu 4.24) server where it will be deployed, it no longer works.
I installed the dblib drivers as described here.
I adapted the code to as required to use the dblib driver so that it would run without errors. This only involved changing the first two lines inside the try statement.
I have changed the first line to:
...
$conn = new PDO("dblib:host=$host;dbname=$db", $user, $password);
...
I have tried all of the following for the second line:
$sql = "{CALL dbo.check_for_barcode(#Sample_Id=:barcode, #Barcode_In_table=:isInDatabase)}";
$sql = "{CALL dbo.check_for_barcode #Sample_Id=:barcode, #Barcode_In_table=:isInDatabase}";
$sql = "CALL dbo.check_for_barcode(#Sample_Id=:barcode, #Barcode_In_table=:isInDatabase)";
$sql = "CALL dbo.check_for_barcode :barcode, :isInDatabase";
As well as all of the above using EXEC instead of CALL
The output in all cases is:
for sample id 11335577 $isInDatabase =
for sample id 0011223344 $isInDatabase =
If I add ...
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
var_dump($result);
}
... this generates no output.
There are no error message at all, so I can't see where the problem is. I would welcome any suggestions on what to try next.
It's been a while since I had to do this, but I used ODBC to connect to SQL Server from PHP running on a linux box.
Drivers - http://msdn.microsoft.com/en-gb/data/ff657782.aspx
ODBC docs - http://www.php.net/manual/en/ref.pdo-odbc.connection.php
EDIT: The ODBC drivers above are for Windows, the Linux installation instructions and drivers can be found at www.php.net/pdo_odbc

PDO code not working

i am new to PDO.. i tried out some online tutorials and found some step-by-step guides. i am using WAMP, i created a database named "try" with table named "books".
Now in my index.php i wrote:
<?php
$host = "localhost:3306";
$db = "try";
$user = "clyde";
$pass = "moonfang";
$conn = new PDO("mysql:host=$host;dbname=$db",$user,$pass);
$sql = "SELECT * FROM books";
$q = $conn->query($sql) or die("failed!");
while($r = $q->fetch(PDO::FETCH_ASSOC)){
echo $r['title'];
}
?>
Now whenever i load localhost on my browser i see these errors;
i dont understand the problem.. :-(
According to several examples it seems that PDO prefers the host and the port in the dsn for itself:
$host = "localhost";
$port = 3307;
$conn = new PDO("mysql:host=$host;port=$port;dbname=$db",$user,$pass);
Here's the PHP manual for the PDO MySQL DSN. Note the "port" part.
The problem is that the target machine actively refused [the connection].
Therefore you have to check if usernames/passwords/access-rights to the database server are all OK; including IP/host and port/firewall settings.
Line 8 where error occurs is $q = $conn->query($sql) or die("failed!"); This line mixes mysql_ and PDO and is not required.
The code should look like
$sql = "SELECT * FROM books";
while($r = $sql->fetch(PDO::FETCH_ASSOC)){
echo $r['title'];
}
You should also incorporate PDO error handling
`

Categories