Php connection with mssql via odbc, wrong encoding - php

I have created mssql connection in php via odbc correctly. I can Insert some data into database but if I want to send some special characters it displayed bad way. I have set UTF-8 charset in my website and UTF-8 file encoding. When i try Insert data from the command line using isql command it works. I've tried already all conversion method but its no effects.

$user = 'admin';
$password = 'pass123';
$dsn = 'mydsn';
$connection = odbc_connect($dsn, $user, $password);
if ($connection) {
$data_array = array(
"string" => "ąĄę12",
);
$sql = "INSERT INTO Table (column_1) VALUES ('".$data_array['string']."')";
$res = odbc_exec($connection, $sql);
if (!$res) {
error_log("Insert failed");
}
odbc_close($connection);
}
else {
die("Connection could not be established.");
}

Related

mySql database connecting to wrong server

I have been trying to setup a Sql database, but I can't get it to connect in php. here's what my code looks like:
$conn = mysql_connect("my_sql_here.net","root",'my_password_here');
print $conn;
mysql_select_db("my_database",$conn);
$created = mysql_query("SELECT * FROM `inventory`);
if(!$created) {
print "error: ";
print mysql_error();
}
print json_encode($created);
mysql_close($conn);
When I run this code, I get:
error: Access denied for user 'dom710'#'localhost' (using password: NO)false
Why is it tryng to connect to localhost? and why is trying to use root as the password?
I am super confused.
Consider using PDO to make a connection:
// Establish a connection
$host = 'my_sql_here.net';
$name = 'my_database';
$user = 'root';
$pass = 'my_password_here';
$dsn = "mysql:dbname=$name;host=$host;charset=utf8";
$conn = new PDO($dsn, $user, $pass);
// Perform your query
$query = 'SELECT * FROM `inventory`';
$statement = $conn->prepare($query);
$statement->execute();
$resultSet = $statement->fetchAll();
// Do stuff with your $resultSet
You have configured safe mode. This is why it tries to connect to localhost.
https://dev.mysql.com/doc/apis-php/en/apis-php-function.mysql-connect.html
$server "In SQL safe mode, this parameter is ignored and value 'localhost:3306' is always used."
$username "In SQL safe mode, this parameter is ignored and the name of the user that owns the server process is used."
And as someone stated in comments you shouldn't use this function because it's deprecated.

Why isn't my PHP connecting to my database or displaying an error?

I am creating a form that will take a person's name and email and see if the email exists in the database already but I can't get the database to be selected. The mysql_error() won't display the error either. Is there something wrong with my code for selecting the database? All it shows is the hardcoded text "Could not select database because" then nothing. I replaced all the variables associated with the database with random fillers so as not to give away my info but everything I have is correct regarding that.
$host = "host";
$user = "user";
$password = "pass";
$database = "db";
$port = xxxx;
$table = "table";
// Create connection
$conn = mysqli_connect($host, $user, $password, $database, $port);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connection Successful";
mysqli_select_db($database)
or die("Could not select database because".mysqli_error());
// check if the username is taken
$check = "select email from $table where email = '".$_POST['email']."';";
$qry = mysqli_query($check)
or die ("Could not match data because ".mysqli_error());
$num_rows = mysqli_num_rows($qry);
if ($num_rows != 0) {
echo "Sorry, there the username $username is already taken.";
}
Don't call mysqli_select_db. You've already selected your database with the fourth parameter to mysqli_connect.
You only need to call mysqli_select_db if you want to access a different database after the connection has been established.
Also, Raptor is correct that if you call procedural mysqli_error() you must pass it a connection handle.
For Procedural style mysqli_error(), you must supply the MySQLi DB link as parameter:
mysqli_select_db($database)
or die("Could not select database because" . mysqli_error($conn));
But it's useless to call mysqli_select_db() as you already specified the DB schema in mysqli_connect().
Additionally, your SQL is vulnerable to SQL Injection attack. Always escape the parameter before putting into SQL statement, or use prepared statements.
try this code
<?php
$username = "your_name";
$password = "your_password";
$hostname = "localhost";
//connection to the database
$dbhandle = mysqli_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
?>

php local connection mysql database

I try to make a simple IOS app that can connect to mysql database and read one table. But my php code does't work and really have no idea why, it's seems correct to me. The database is in a raspberry phpmyadmin server and the server works great.
I will put my code here and please tell me what's wrong.
<?php
$host = "192.168.2.193";
$db = "produtos";
$user = "root";
$pass = "1234";
$connection = mysql_connect($host, $user, $pass);
if(!$connection)
{
die("Database server connection failed.");
}
else
{
//attempt to select the database
$dbconnect = mysql_select_db($db, $connection);
//check to see if we could select the database
if(!dbconnect)
{
die("Unable to connect to the specified database!");
}
else
{
$query = "SELECT * FROM produtos";
$resultset = mysql_query($query, $connection);
$records = array();
//loop throught all our records and add them to our array
while ($r = mysql_fetch_assoc($resultset))
{
$records[] = $r;
}
echo json_ecode($records);
echo $resultset;
}
}
?>
Based on the question:
use mysqli_connect rather than mysql_connect because mysql_connect is deprecated and will not work someday. Also what is the the error you are getting? change your die() statement to something more helpful die(mysqli_error($connection));
Based on your comment:
That error would suggest that you either A) don't have the right IP address or B) there is a network issue between your host server and the SQL server, is this code running on the same server that is hosting the SQL database? if so then you can probably just use localhost for your $host

Trying to get MySQL to connect via php into JSON, but returning errors connecting to MySQL from a php script

Essentially, I am trying to print out information in JSON so that I can communicate with my app, but I cannot connect to the MySQL database from a php script for some odd reason. What could it be that causes the error:
Warning: mysql_connect() [function.mysql-connect]: Lost connection to MySQL server during query in /srv/disk11/1158855/www/(myphpwebsite)/lib.php on line 13
Could not connect: Lost connection to MySQL server during query.
Also, line 13 is indicating the line in lib.php:
mysql_connect ( $dbhost, $dbuser, $dbpass) or die("Could not connect: ".mysql_error());
It should also be noted that this is a followup to a previous question in case anyone wanted to track down the source: MySQL issue connecting to site with php.
Lastly, I get the same error from both a localhost and a remote server using mysql
lib.php
<?
//Database Information
$dbhost = "31.170.160.76";
$dbname = "testdatabase";
$dbuser = "(personalinformation)";
$dbpass = "tested123";
//Connect to database
mysql_connect ( $dbhost, $dbuser, $dbpass) or die("Could not connect: ".mysql_error());
mysql_select_db($dbname) or die(mysql_error());
//executes a given sql query with the params and returns an array as result
function query() {
global $link;
$debug = false;
//get the sql query
$args = func_get_args();
$sql = array_shift($args);
//secure the input
for ($i=0;$i<count($args);$i++) {
$args[$i] = urldecode($args[$i]);
$args[$i] = mysqli_real_escape_string($link, $args[$i]);
}
//build the final query
$sql = vsprintf($sql, $args);
if ($debug) print $sql;
//execute and fetch the results
$result = mysqli_query($link, $sql);
if (mysqli_errno($link)==0 && $result) {
$rows = array();
if ($result!==true)
while ($d = mysqli_fetch_assoc($result)) {
array_push($rows,$d);
}
//return json
return array('result'=>$rows);
} else {
//error
return array('error'=>'Database error');
}
}
//loads up the source image, resizes it and saves with -thumb in the file name
function thumb($srcFile, $sideInPx) {
$image = imagecreatefromjpeg($srcFile);
$width = imagesx($image);
$height = imagesy($image);
$thumb = imagecreatetruecolor($sideInPx, $sideInPx);
imagecopyresized($thumb,$image,0,0,0,0,$sideInPx,$sideInPx,$width,$height);
imagejpeg($thumb, str_replace(".jpg","-thumb.jpg",$srcFile), 85);
imagedestroy($thumb);
imagedestroy($image);
}
?>
Index.php
<?
session_start();
require("lib.php");
require("api.php");
header("Content-Type: application/json");
switch ($_POST['command']) {
case "login":
login($_POST['username'], $_POST['password']); break;
case "register":
register($_POST['username'], $_POST['password']); break;
}
exit();
?>
api.php
<?php
function errorJson($msg){
print json_encode(array('error'=>$msg));
exit();
}
function register($user, $pass) {
//check if username exists
$login = query("SELECT username FROM login WHERE username='%s' limit 1", $user);
if (count($login['result'])>0) {
errorJson('Username already exists');
//try to register the user
$result = query("INSERT INTO login(username, pass) VALUES('%s','%s')", $user, $pass);
if (!$result['error']) {
//success
login($user, $pass);
} else {
//error
errorJson('Registration failed');
}
}
}
function login($user, $pass) {
$result = query("SELECT IdUser, username FROM login WHERE username='%s' AND pass='%s' limit 1", $user, $pass);
if (count($result['result'])>0) {
//authorized
$_SESSION['IdUser'] = $result['result'][0]['IdUser'];
print json_encode($result);
} else {
//not authorized
errorJson('Authorization failed');
}
}
?>
As this is on the "connect" line, the server has been found (otherwise you get a different message) but you've not negotiated your log in.
Straight from the manual:
More rarely, it can happen when the client is attempting the initial connection to the server. In this case, if your connect_timeout value is set to only a few seconds, you may be able to resolve the problem by increasing it to ten seconds, perhaps more if you have a very long distance or slow connection.
If that isn't it, it's either a network problem or your connection has been terminated mid-authentication. Check that your mysql host doesn't have some weird validation that you're coming from a particualr IP (I say weird, as there are more standard ways of managing it than killing the authentication mid-flow), or try your PHP script from a a server that is closer to the MySQL server (closer in terms of network speed).
I figured out what was the matter. It turns out that my php code further down was conflicting with the login. That's why it wouldn't authenticate on multiple remote MySQL's and my own Localhost

How to check if my ODBC Data Source exist in PHP?

I have a simple project and that is to create a function that will check for mysql and odbc connection. I'm already done in creating the function for mysql, here's my sample code:
function check() {
$serverName = 'localhost';
$userName = 'root';
$password = '123';
$db = 'sample';
$conn = mysql_connect($serverName, $userName, $password);
mysql_select_db($db, $conn);
$trans = 'SELECT * FROM Labels';
$trans_result = mysql_query($trans, $conn);
if(!$trans_result) {
die(mysql_error());
} else {
echo "connected";
}
}
Well this one works for me when checking for the mysql connection. Now, my question is, is it possible to create something like this for checking my odbc data source connection? So that would be like
$conn = odbc_connect("spmuse1","" ,""); # Open connection.
$trans = "SELECT French FROM Labels";
$trans_result = odbc_exec($conn, $trans);
if(!$trans_result) {
echo "error?";
} else {
echo "connected";
}
You know what I mean? When I use this code, I always have 2 this error
Warning: odbc_connect() [function.odbc-connect]: SQL error: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified, SQL state IM002 in SQLConnect
Warning: odbc_exec(): supplied argument is not a valid ODBC-Link resource
Please help! Thanks.
First you need to decide vendor of odbc driver, I hope below example will works for you
<?php
// Configure connection parameters
$db_host = "server.mynetwork";
$db_server_name = "Dev_Server";
$db_name = "Dev_Data";
$db_file = 'c:\dbstorage\dev.db';
$db_conn_name = "php_script";
$db_user = "dbuser";
$db_pass = "dbpass";
$connect_string = "Driver={Adaptive Server Anywhere 8.0};".
"CommLinks=tcpip(Host=$db_host);".
"ServerName=$db_server_name;".
"DatabaseName=$db_name;".
"DatabaseFile=$db_file;".
"ConnectionName=$db_conn_name;".
"uid=$db_user;pwd=$db_pass";
// Connect to DB
$conn = odbc_connect($connect_string,'','');
// Query
$qry = "SELECT * FROM my_table";
// Get Result
$trans_result= odbc_exec($conn,$qry);
if(!$trans_result) {
echo "error?";
} else {
echo "connected";
}
?>
I spent several days looking for a simple answer, and came up with this, which works for me:
if (#odbc_connect("DBName","un","pw",SQL_CUR_USE_ODBC) == FALSE){
echo "Database does not exist";
} else {
$connection=odbc_connect("DBName","un","pw",SQL_CUR_USE_ODBC);
echo "Database exists";
}
The # suppresses the basic error if the database does not exist, so the connection try will just return false. Of course if the connection is good, then it creates the connection object.

Categories