How to connect mssql with php 7.2.5 - sql-server-2008

I've worked with a system on Ubuntu server 17. But after I've upgraded to 18.04 LTS, my mssql connection stopped working.
This is my following program line:
$serverName = "IP OF MY SERVER";
$connectionOptions = array(
"Database" => "DB NAME",
"Uid" => "USER",
"PWD" => "PASSWORD"
);
//Establishes the connection
$conn = sqlsrv_connect($serverName, $connectionOptions);
//Select Query
$tsql = "SELECT ##Version as SQL_VERSION";
//Executes the query
$getResults = sqlsrv_query($conn, $tsql);
//Error handling
if ($getResults == FALSE)
die(FormatErrors(sqlsrv_errors()));
sqlsrv_free_stmt($getResults);
function FormatErrors($errors) {
/* Display errors. */
echo "Errors: <br/>";
foreach ($errors as $error) {
echo "SQLSTATE: " . $error['SQLSTATE'] . "<br/>";
echo "Code: " . $error['code'] . "<br/>";
echo "Message: " . $error['message'] . "<br/>";
}
}
The current version of my php is 7.2.5.
What should I do considering that everything is updated?

In the last version I hadn't to manually install the ssql driver.
But in the newest version of Ubuntu it's necessary.
After installed by following these procedures PROCEDURES it has working again.

You can connect this way.
Syntax
connection mysql_connect(server,user,passwd,new_link,client_flag);
EX
<?php
$dbhost = 'localhost:3306';
$dbuser = 'guest';
$dbpass = 'guest123';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($conn);
?>

Related

How to make reference to one of my MySQL databases inside my PHP file?

I have already asked this related question: https://webmasters.stackexchange.com/questions/116055/using-mysql-database-data-directly-into-generating-articles-for-my-website-new/116056?noredirect=1#comment154341_116056
At this point, I'm starting to understand the code syntax and project structure a little better.
But I have made my database using MySQL console. it only has a few entries so far, I wanted to try to adapt the code in Zach's example, but here is the problem I have:
The problem is, I am unsure how to get the reference to my database object? In the code sample from Zach there is variable $db, I guess this is where i need to keep a reference to my own actual database.
Here is the psuedo-code (maybe) from Zach, note: he always said to me not to copy-paste it, but I'm just trying to see how I can use it in my project.
<?php
$SQL_Query = "SELECT * FROM your_table";
$SQL_Run = mysqli_query($db, $SQL_Query);
while ($row = mysqli_fetch_assoc($SQL_Run)) {
echo
"<section class='wrapper style1'>
<div class='inner'>
<header class='align-center'>
<h2>" . $row['imageurl'] . "</h2>
<img src='" . $row['title'] . "'>
<p>" . $row['description'] . "</p>
</header>
</div>
</section>";
}
?>
So my question simply at moment is: How to create the reference $db?
Your answer is the correct way to establish a connection. I want to point out that there are two ways of writing that statement. The version you found online is one way, but from our previous conversation, you can write it like this:
<?php
// Establish how to log in
$servername = "127.0.0.1";
$username = "root";
$password = "yourpasswordhere";
$dbname = "yourdatabasenamehere";
// create the database connection
$db = new mysqli($servername, $username, $password, $dbname);
// if it fails, kill the site.
if (mysqli_connect_error($db)) {
die("Connection failed: " . mysqli_connect_error($db));
}
// your first query to grab all the article data
$SQL_Query = "SELECT * FROM your_table";
// run the query
$SQL_Run = mysqli_query($db, $SQL_Query);
// while data exists (it makes sure that you have post data, otherwise nothing shows up)
while ($row = mysqli_fetch_assoc($SQL_Run)) {
echo
"<section class='wrapper style1'>
<div class='inner'>
<header class='align-center'>
<h2>" . $row['imageurl'] . "</h2>
<img src='" . $row['title'] . "'>
<p>" . $row['description'] . "</p>
</header>
</div>
</section>";
}
// Close the connection
mysqli_close($db);
?>
You will notice that the connections are written like a function.
mysqli_num_rows($result);
instead of
$result->num_rows
Both do the same thing, just a personal preference. That should hopefully clear some things up from your first post :)
I have got further on and I think have answered my own question. I found it a bit tricky to research because I don't understand all the different terms and names of features/api/scripts/etc. But I had just to read the documentation for mysqli_connect(), I set up the code as follows and now I have pulled all the data from the database into words on my html/php files.
From here I think I can rewrite the code to first sort it by date and then can of course put the latest posts at the top of each page etc.
I can also allow the user to click 'Genre' and only view Comedy for example.
Here is the code just to get the data parsed into my index.php file:
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "yourpasswordhere";
$dbname = "yourdatabasenamehere";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, type, title FROM releases";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Type: " . $row["type"]. " - Title " . $row["title"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
I extended upon the above work by making the php script fetch all the entries in the database and create the previous html article I had once for each entry. In the SELECT statement I can control which types of entries are displayed (eg. For a certain category). Here was how I did it:
// make an html article based snippet (image, title, description, etc),
//once for each entry in the database table...
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "somepassword";
$dbname = "somedatabasename";
// create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// check connection
if ($conn->connect_error) {
die("connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM releases ORDER BY id DESC";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc())
{
echo '<section class="wrapper style1">';
echo '<div class="inner">';
echo '<header class="align-center">';
echo '<h2>'. $row["title"] . '</h2>';
echo '<div class="image fit">';
echo '<img src='. $row["imgurl"] .'>';
echo '</div> <p> RELEASE TITLE: ' . $row["title"] . '<br /> DATE POSTED: ' . $row["postdate"] . '<br /> DESCRIPTION: ' . $row["description"] . '</p>';
echo 'DOWNLOAD LINK: '.$row["link"].' <br />';
$NfoLink = $row["nfolink"];
if ($NfoLink != 'not found' && $NfoLink != '')
{
echo 'NFO LINK/MORE DOWNLOADS: '.$row["nfolink"].'';
}
echo '</header>';
echo '</div>';
echo '</section>';
}
}
else
{
echo "0 results";
}
$conn->close();
?>

PDO vs ODBC for MS Access connection

Would like to know the best practice for connecting to both MySQL and MS Access databases from hosted website. I have an existing site that has been using an MS Access DB for the past 15 years. Hundreds of pages have connection string to the DB, some are DAO, some OLEDB, and others ADO. I'm in the process of trying to move the entire DB over to MySQL but can't move it all at once. Things i'm considering in the move:
Link Tables in Access to the new MySQL and move data over
Rewrite all pages in PHP and use PDO connection (usable on both Access / MySQL)
Use ODBC connection on both (What are advantages vs disadvantages)
Use existing .NET pages with PDO connection to MySQL.
My desire is to eventually use MySQL DB in place of MS Access but the transition will take months to complete. I need to keep site active until all connection pages are rewritten to connect to MySQL (in PHP)
The attached code is working connection to both DB's - both have limitations to methods available. (Example LIMIT will not work on Access, and CROSSTAB/PIVOT will not work on MySQL)
I'm looking for recommendation on how to accomplish this task of moving over...
helpful post about linking: MS access 2010 ODBC connection to MySQL
<html>
<head>
<title>PHP and ODBC: PDO Example </title>
</head>
<body>
<?php
/////////////////////////////////////////// ACCESS PDO //////////////////////////////////////////////////////
try{
$mdbFile = "e:\Training.mdb";
$pdo = new PDO("odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=$mdbFile", "", "");
$query = $pdo->prepare("SELECT * FROM Users WHERE UserName LIKE 'Bar%'");
$query->execute();
echo "<table class='table table-striped table-bordered table-hover table-condensed'>";
echo "<thead><tr>";
echo "<th>AutoNum</th><th>User Name</th><th>Email</th>";
echo "</tr></thead>";
for($i=0; $row = $query->fetch(); $i++){
echo "<tbody><tr>";
echo "<td>".$row['AutoNum']."</td>";
echo "<td>".$row['UserName']."</td>";
echo "<td>".$row['Email']."</td>";
}
echo "</tr></tbody></table>";
unset($pdo);
unset($query);
} catch (PDOException $e) {
echo "Failed to get DB handle: " . $e->getMessage() . "\n";
exit;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////// MYSQL ODBC //////////////////////////////////////////////////
// *** THIS WORKS - DON'T CHANGE ***
//$mdbFilename = "e:\Training.mdb";
//$user = "";
//$password = "";
//$connection = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$mdbFilename", $user, $password);
$user = "user";
$password = "password";
$connection = odbc_connect("Driver={MySQL ODBC 5.1 Driver};SERVER=$mdbFilename; database=MYSQL_training", $user, $password);
if (!$connection) {
echo "Couldn't make a connection!";
exit;
}
$sql = "SELECT * FROM Users WHERE UserName LIKE 'Bar%'";
$process=odbc_exec($connection, $sql);
echo "<br><br><br>";
echo "<table class='table table-striped table-bordered table-hover table-condensed'>";
echo "<thead><tr>";
echo "<th>AutoNum</th><th>User Name</th><th>Email</th>";
echo "</tr></thead>";
while(odbc_fetch_row($process)){
$username = odbc_result($process, "UserName");
$email = odbc_result($process, "Email");
$autonum = odbc_result($process, "AutoNum");
echo "<tbody><tr>";
echo "<td>".$autonum."</td>";
echo "<td>".$username."</td>";
echo "<td>".$email."</td>";
}
echo "</tr></tbody></table>";
odbc_close($connection);
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////// MYSQL PDO///////////////////////////////////////////////////////
$db_mysql = "mysql_training";
$user = "user";
$password = "password";
$pdo = new PDO("odbc:Driver={MySQL ODBC 5.1 Driver};SERVER=$mdbFilename; database=$db_mysql", $user, $password);
try{
$query = $pdo->prepare("SELECT * FROM Users WHERE UserName LIKE 'Bar%' LIMIT 3");
$query->execute();
echo "<br><br><br>";
echo "<table class='table table-striped table-bordered table-hover table-condensed'>";
echo "<thead><tr>";
echo "<th>AutoNum</th><th>User Name</th><th>Email</th>";
echo "</tr></thead>";
for($i=0; $row = $query->fetch(); $i++){
echo "<tbody><tr>";
echo "<td>".$row['AutoNum']."</td>";
echo "<td>".$row['UserName']."</td>";
echo "<td>".$row['Email']."</td>";
}
echo "</tr></tbody></table>";
unset($pdo);
unset($query);
} catch (PDOException $e) {
echo "Failed to get DB handle: " . $e->getMessage() . "\n";
exit;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
?>
</body>
</html>

Qt isOpen method false value MySQL

I have a MySQL database, which i created in Workbench. I can easily connect to it using php code:
<?php
$host = "localhost";
$port = 3306;
$socket = "";
$user = "hate";
$password = "88005553535";
$dbname = "galleries_db";
$con = new mysqli($host, $user, $password, $dbname, $port, $socket)
or die ('Could not connect to the database server' . mysqli_connect_error());
echo "DONE!";
?>
But when I'm trying to connect to my DB with Qt like this:
QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
db.setHostName("localhost");
db.setPort(3306);
db.setDatabaseName("galleries_db");
db.setUserName("hate");
db.setPassword("88005553535");
db.open();
if(!db.isOpen()) {
ui->label->setText("-");
qDebug() << "Error: "<< db.lastError() << " " << db.lastError().text();
}
else
ui->label->setText("+");
I always get false value returned by isOpen method. And in stream I have:
Error: QSqlError("", "", "") " "
May be problem in MySQL driver for Qt ? Or there is something else ?
Will appriciate any help or advice.
There should be:
if(db.isOpen())
Not:
if(!db.isOpen())
Actually it is very silly mistake. isOpen always returned me true value, and I made it false by myself.

Table dosent exist

I keep getting this error when i try and run some mysql code from a php file on my server :
Table 'leaderboard.u' doesn't exist
The thing is that the table leaderboard does exist . Its been setup the same way that I have it setup in xampp . It also works on xampp and worked on the server until recently .
What could be causing this ?
EDIT :
<?php
include("../../config/connect.php");
if(!empty($_GET['id']) && !empty($_GET['data']))
{
$id = $_GET['id'];
$data = $_GET['data'];
$key = $_GET['key'];
$result = mysqli_query($connection,"update userbadges set $key='$data' where id='$id'");
if(!$result) {
echo mysqli_error($connection);
exit;
}
echo 'database update ' . mysqli_affected_rows($connection) . ' rows';
}
?>

Warning: mysql_select_db() expects parameter 2 to be resource,

<?php
$servername = "localhost";
$username = "root";
$password = "Rachel";
$db = "hairdressingapointments";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected Sussessfully";
mysql_select_db('Hairdressingapointments', $conn) or die(mysql_error());
$sql = "SELECT `ApointmentDate`, `ApointmentTime` FROM `apointments` WHERE `staff_id`=1 && `quantity`>0";
if(!mysql_query($sql)){
die('Error: ' . mysql_error());
}
echo $sql;
mysql_close();
?>
spent hours trying to figure this out and im guessing its something so simple. getting back the following error:
Warning: mysql_select_db() expects parameter 2 to be resource, object given in C:\wamp2\www\hairdressingapointments\TeresaApointments.php on line 15 which is,
mysql_select_db('Hairdressingapointments', $conn) or die(mysql_error());
You already connected to the database using
mysqli_connect(...);
So, you do not need
mysql_select_db(....);
Also change the query to this
$sql = "SELECT ApointmentDate, ApointmentTime FROM apointments WHERE staff_id=1 AND quantity>0";
If you use SQLWorkbench or SQLYog or some other tool, you can enter your SQL and make sure it is valid before adding it to your script.
Also, make sure the table name is really
apointments
and not
appointments
I got this information from php.net - mysqli_connect