IIS, MS SQL and PHP - SQL select in PHP not working - php

I have a local MS SQL Database, and a web PHP application on IIS on my server.
On IIS I have successfully connected PHP and my MS SQL database (added connection strings and i see my tables)
But, when I use any SQL select in the PHP web application, it does not work. No data is displayed, or any erros, for example :
/* Connect to a MySQL database using driver invocation */
$dsn = 'mysql:dbname=dbname;host=localhost';
$user = 'dbuser';
$password = 'dbpass';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$results = mysql_query("SELECT id FROM users");
while($row = mysql_fetch_array($results)) {
$name = $row['id']
?>
<tr>
<td><?php echo '$name'?></td>
</tr>
<?php
}
?>
</tbody>
</table>

follow like this for pdo connection
$sql = $dbh->prepare("SELECT id FROM users");
$sql->execute();
while($result = $sql->fetch(PDO::FETCH_ASSOC)){
?>
<tr>
<td><?php echo $result['name'];?></td>
</tr>
<?php } ?>

Please follow that code:
$host = '127.0.0.1';
$db = 'test';
$user = 'root';
$pass = '';
$charset = 'utf8';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt =
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$pdo = new PDO($dsn, $user, $pass, $opt);
$stmt = $pdo->query('SELECT name FROM users');
while ($row = $stmt->fetch())
{
echo $row['name'] . "\n";
}

MS SQL (or SqlSrv) and MySql are not working on the sames drivers. You have to know which one you are using and the find PHP functions ables to deal with it.
Note: PHP Extension for using driver must be installed on your server and activated on php.ini file
For MySql do not use mysql_xxx() deprecated functions, prefer mysqli_xxx() to them.
You can find here docs and samples code for both mysql & mssql php functions :
MySql :
http://php.net/mysqli_connect
php.net/mysqli_fetch_array
SqlSrv :
http://php.net/sqlsrv_connect
php.net/sqlsrv_fetch_array
So what is your database engine ?
Hope that'll helps you, cheers

Mixing the apis would not work - use only PDO methods like this perhaps
/* Connect to a MySQL database using driver invocation */
try {
/* mysql server */
/* $dsn = 'mysql:dbname=dbname;host=localhost'; */
/* MS SQL Server */
$dsn = 'sqlsrv:Database=dbname;Server=localhost';
$user = 'dbuser';
$password = 'dbpass';
$dbh = new PDO($dsn, $user, $password);
$sql='select * from users';
$results=$dbh->query( $sql );
if( $results ){
while( $rs=$results->fetch( PDO::FETCH_OBJ ) ){
echo "<tr><td>{$rs->name}</td></tr>";
}
}
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}

Now working great also with select, with this code :
<?php
$serverName = "AC-CLOUD"; //serverName\instanceName
$connectionInfo = array( "Database"=>"Data", "UID"=>"sa", "PWD"=>"Masterkey2010");
$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));
}
$sql = "SELECT Code, Name FROM StoreCards";
$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['Code'].", ".$row['Name']."<br />";
}
sqlsrv_free_stmt( $stmt);
?>
How now i set this two values into table? this is last point. thank you for your patience and time.

Related

How do I reconnect my web pages on my website after updating to PHP 7 with a MySQL database 5.0.0?<?

I added the i updates to communicate with the database & now the page links don't work.
<?php
// Connect to database
$link=mysqli_connect('localhost', 'xxxxx', 'xxxxx');
mysqli_select_db($link, 'waddellc_PHRDB');
$sql = "SELECT * FROM quotes ORDER BY id";
$result = mysqli_query($link, $sql) or die(mysql_error());
$tenant_quotes = array();
$owner_quotes = array();
while($row = mysqli_fetch_array($result)) {
This should do the work, using PDO :
$servername = "localhost";
$username = "username";
$password = "password123";
$conn = null;
try {
$conn = new PDO("mysql:host=$servername;dbname=databaseName", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
if(!is_null($conn)){
$stmt = $conn->prepare("SELECT * FROM quotes ORDER BY id");
if ($stmt->execute()) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}
}
I also think you need to update your database, it's quite old now.

Azure web app with mysqli_connect instead of PDO

I have recently been successful with utilize the PDO connection instead of mysql_query, however I find PDO to be far complex and confusing, so I wish use the mysqli/mysqlconnet instead.
I noticed that uppgrading the php version on the azure app decerese the potenial error you can get, however I was wondering how can you make your app as close to as the localhost variation, with error been extremtly precise and simple to understand?
Here is the code mysql_querry con
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$conn = mysqli_connect($servername, $username, $password);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
if ($result = mysqli_query($link, "SELECT * FROM City", MYSQLI_USE_RESULT)) {
if (!mysqli_query($link, "SET #a:='this will not work'")) {
printf("Error: %s\n", mysqli_error($link));
}
mysqli_free_result($result);
}
mysqli_close($link);
?>
PDO variation
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
<?php
function getFruit($conn) {
$sql = 'SELECT name, color, calories FROM fruit ORDER BY name';
foreach ($conn->query($sql) as $row) {
print $row['name'] . "\t";
print $row['color'] . "\t";
print $row['calories'] . "\n";
}
}
?>
Here is the app settings
web app settings
Also what is the diffrent between utlizeing Connection String here
mysql connection
compare to utilize the php implmetion within in webmatrix
UPDATE here what I am basically trying to get to work. But I dunno why azure doesnt give me errors or anything. I have finally figured out that you can go into the console/kudu and change the php ini file
$query = "SELECT * FROM randomTable WHERE innhold LIKE '%$searchFunction%';";
$result = mysqli_query($conn, $query) or die("Ikke mulig og søke i db");
$antallrader = mysqli_num_rows($sqlResultat);
As a production environment, Azure Web Apps Service do not enable the display errors in PHP runtime. For dev, you can config the setting display_errors in PHP ini config file. You can refer to How to: Change the built-in PHP configurations
for details.
Meanwhile, you can simply add the following code in your PHP script to enable to show the errors:
error_reporting(E_ALL);
ini_set('display_errors', 'On');
And BTW, the PHP runtime on Azure Web Apps has supported the mysqli extension even in PHP 7.0. You can use phpinfo() to check all PHP runtime.
Any further concern, please feel free to let me know.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "test";
$charset = "utf8";
// mysqli version
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = mysqli_connect($servername, $username, $password, $dbname);
$conn->set_charset($charset)
$result = $conn->query("SELECT * FROM City");
$data = [];
while($row = $result->fetch_assoc())
{
$data[] = $row;
}
foreach ($data as $row)
print $row['name'] . "\t";
print $row['color'] . "\t";
print $row['calories'] . "\n";
}
// PDO version
$dsn = "mysql:host=$servername;dbname=$dbname;charset=$charset";
$conn = new PDO($dsn, $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$data = $conn->query("SELECT * FROM City");
foreach ($data as $row)
print $row['name'] . "\t";
print $row['color'] . "\t";
print $row['calories'] . "\n";
}
For the life of me I won't understand how is PDO version more confusing.

Insert values in table (mssql server) via PhP by using pdo

I could not insert values in table (MSSQL) by using pdo php. I got message that connection is established but query does not work. I have never used MSSQL server I am not sure is this query good.
$database = "db";
$server = "xxx\SQLEXPRESS";
$conn = array( "Database"=>"db", "UID"=>"user", "PWD"=>"xxx" , "CharacterSet" => "UTF-8");
if( $conn ) {
echo "connection established";
}else{
echo "Connection could not be established.";
die( print_r( sqlsrv_errors(), true));
}
// insert values into table,
// variables are defined above didnt write them here
$query = $conn->prepare("INSERT INTO dbo.FKNarudzbaKupacaStavke(IdFirma, VrstaDokumenta, BrojDokumenta, BrojDokumentaKroz,
DatumDokumenta, IdKupac, VrstaCijene, NacinPlacanja, DatumZadnjeAkcije, Status, StatusArhive, StatusIzmjene,
StatusStampe, VrstaFakture) VALUES(:IdFirma, :VrstaDokumenta, :BrojDokumenta, :BrojDokumentaKroz, :DatumDokumenta, :IdKupac, :VrstaCijene, :NacinPlacanja,
:DatumZadnjeAkcije, :Status, :StatusArhive, :StatusIzmjene, :StatusStampe, :VrstaFakture)");
$query->bindParam(':IdFirma',$IdFirma);
$query->bindParam(':VrstaDokumenta',$VrstaDokumenta);
$query->bindParam(':BrojDokumenta',$BrojDokumenta);
$query->bindParam(':BrojDokumentaKroz',$BrojDokumentaKroz);
$query->bindParam(':DatumDokumenta',$DatumDokumenta);
$query->bindParam(':IdKupac',$IdKupac);
$query->bindParam(':VrstaCijene',$VrstaCijene);
$query->bindParam(':NacinPlacanja',$NacinPlacanja);
$query->bindParam(':DatumZadnjeAkcije',$DatumZadnjeAkcije);
$query->bindParam(':Status',$Status);
$query->bindParam(':StatusArhive',$StatusArhive);
$query->bindParam(':StatusIzmjene',$StatusIzmjene);
$query->bindParam(':StatusStampe',$StatusStampe);
$query->bindParam(':VrstaFakture',$VrstaFakture);
$query->execute();
I got this error :
Fatal error: Call to a member function prepare() on a non-object..
Any help or advice is appreciated!
The way you've written it, $conn isn't a connection, it's just an array.
Try this to connect to the database:
$hostname = 'xxx\SQLEXPRESS';
$username = 'user';
$password = 'xxx';
$dbname = 'db';
$conntype = 'mysql'; //or dblib or mssql
try {
$conn = new PDO("$conntype:host=$hostname;dbname=$dbname", $username, $password);
}
catch( PDOException $e ) {
echo( $e->getMessage() );
}
You are actually not establishing the connection there, please change your $conn variable as show below
$conn = new PDO("mssql:host=".$server.";dbname=db", "user", "xxx");

connect to sql database with php

Im trying to connect to sql database with PHP.For some reason when i run the code i am getting below error.
Parse error: syntax error, unexpected '$result' (T_VARIABLE) in C:\xampp2\htdocs
\tutorials\abb.php on line 13
My Code is this...
$user = 'root' ;
$pass = 'xcvsdffd' ;
$db = 'testdb' ;
$con = new mysqli('localhost', $user , $pass , $db) or die("UNABLE TO CONNECT");
$selected = mysql_select_db($db,con)
$result = mysql_query("SELECT * FROM test");
while ($row = mysql_fetch_array($result)) {
echo "ID:".$row{'id'}." Name:".$row{'name33'}."
".$row{'year'}."<br>";
}
//close the connection and recordset objects freeing up resources
$result->Close();
$con->Close();
$result = null;
$con = null;
?>
There are two reasons which was the reason for your errors..
1.
You missed a semicolon ; and a $ sign. Below is valid one.
$selected = mysql_select_db($db,$con); //Replace this with your existing line.
2.
You are mixing mysql_* and mysqli_*
Sidenote:
This(mysql_*) extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. Switching to PreparedStatements is even more better to ward off SQL Injection attacks !
The PDO way...
<?php
$dsn = 'mysql:dbname=testdb;host=localhost';
$user = 'root';
$password = 'xcvsdffd';
try
{
$dbh = new PDO($dsn, $user, $password ,array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
For more information.. read the PHP Manual. or use PreparedStatements in MySQLi
Mysqli works with MySQL version 4.1.13 or newer; if your version is old then u should connect your db the old way like this:
$con=mysql_connect("localhost","root","pass");
mysql_select_db("database_name",$con);
They always tell me that MySQL command is now depreciated or something. That's why it's a good practice to use PDO or MySQLI. It's easy to use, if you'll appreciate it's use.
Now going to your code:
$connection = new mysqli("localhost","user","password","database name");
$selectDatabase = mysqli_select_db($connection,"database name");
$connection->query ("SELECT * FROM test");
Hope this helps
Try this below , if you are creating mysqli connection then you dont have to use mysql_select_db($db,con) for again select database. or use semicolon after this line
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* return name of current default database */
if ($result = $mysqli->query("SELECT DATABASE()")) {
$row = $result->fetch_row();
printf("Default database is %s.\n", $row[0]);
$result->close();
}
/* change db to world db */
$mysqli->select_db("world");
/* return name of current default database */
if ($result = $mysqli->query("SELECT DATABASE()")) {
$row = $result->fetch_row();
printf("Default database is %s.\n", $row[0]);
$result->close();
}
$mysqli->close();
?>
Reference
there might be a semicolon missing in a line .
mysql_select_db($db,$con);
Try this
<?php
$username = 'root';
$pass = 'pass';
$db = 'db';
$link = mysqli_connect('localhost',$username,$pass,$db);
if(!link){
echo "Not Connected to DB" . mysqli_connect_error();
$result = mysqli_query($link, "SELECT * FROM test");
while($row = mysqli_fetch_array($result)){
echo "ID: " . $row['id'];
echo "Name: " . $row['name33'];
echo "Year: " . $row['year'];
}
?>
Querying in PHP must be consistent, meaning if you use mysqli you should use it throughout the PHP file, and if you use mysqli you must also use it throughout the PHP file. mysqli and mysql also has different code constructions. So search on the web for their proper construction. Hope this helps

Having problems connecting to mssql server

Code I'm using to test connection:
$serverName = 'host\sqlexpress';
$database = 'dbname';
// Get UID and PWD from application-specific files.
$uid = 'username';
$pwd = 'password';
try {
$conn = new PDO( "sqlsrv:server=$serverName;Database = $database", $uid, $pwd);
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch( PDOException $e ) {
die( "Error connecting to SQL Server" );
}
echo "Connected to SQL Server\n";
$query = 'select * from tablename';
$stmt = $conn->query( $query );
while ( $row = $stmt->fetch( PDO::FETCH_ASSOC ) ){
print_r( $row );
}
// Free statement and connection resources.
$stmt = null;
$conn = null;
?>
The error I'm getting when running this file is just, "Error connecting to SQL Server"
Any clue why this may not be working? Any way I can get a more detailed error report?

Categories