PHP - Access MS SQL View and Echo Results - php

I'm trying to access and read a view from a MS SQL database with PHP. For now I'm just trying to echo out the results on the screen. When I test, my page shows nothing at all.
This is what I have:
<?php
$myServer = "localhost";
$myUser = "username1";
$myPass = "password1";
$myDB = "database1";
//connect to database
$dbhandle = mssql_connect($myServer, $myUser, $myPass)
or die("Couldn't connect to SQL Server on $myServer");
//select database
$selected = mssql_select_db($myDB, $dbhandle)
or die("Couldn't open database $myDB");
//declare statement
$query = "SELECT ProductId";
$query .= "FROM Inventory ";
$query .= "WHERE UPC='15813658428' and ManufacturerID=465";
//execute the query
$result = mssql_query($query);
$numRows = mssql_num_rows($result);
echo "<h1>" . $numRows . " Row" . ($numRows == 1 ? "" : "s") . " Returned </h1>";
//display results
while($row = mssql_fetch_array($result))
{
echo "<li>" . $row["id"] . $row["name"] . $row["year"] . "</li>";
}
//close
mssql_close($dbhandle);
?>

Often when you get a completely blank output from PHP, it is because the server encountered a problem when parsing or interpetting your code. The best way to deal with this when you are getting no other errors is to strip out (or comment out) large blocks of your code and to use numeric echo statements to verify that the code you have not stripped out is executing. Then slowly add more and more of the code back in.
In this specific case, I am guessing that the problem may come down to the spaces after the ?> in your php file. That can confuse servers. Try removing the ?> completely.
If that still results in no output, then comment out everything after $myDB = "database1";, add an echo statement right before the commenting, and slowly move code back into the uncommented section until you find the line that causes the problem.

Related

Converting from mysql _query to mysqli_query [duplicate]

This question already has answers here:
How to change mysql to mysqli?
(12 answers)
Closed 3 years ago.
I have many simple PHP files with MySQL queries that I need to modify since my webhost migrated from PHP5 -> PHP7. I am pretty much a PHP/MySQL beginner trying to wrap my head around the changes from MySQL to MySQLi.
I've begun reading the PHP docs re: MySQLi but am getting stuck on mysqli_query at the moment.
Here is the MySQLi code I've tried so far:
<?php
$con = mysqli_connect("localhost”, “my_user","my_password,"my_db”);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$result = mysqli_query("SELECT image, caption
FROM tbllinkcat, tblimages
WHERE tbllinkcat.catid = tblimages.catid
AND tbllinkcat.catid=1;");
while($row = mysql_fetch_array($result))
{
echo $row['image'];
echo "<br />";
echo $row['caption'];
echo "<br />";
}
mysql_close($con);
?>
I'm pretty sure the mysqli_connect code is working but I get errors on the mysqli_query code (error: Warning: mysqli_query() expects at least 2 parameters.
And I am pretty sure I will get errors on the mysql_fetch_array too once I correct mysqli_query. So for now I was wondering if someone could just show me an example of a mysqli_query that would work for the specific SQL statements in my code above? I will continue reading the PHP docs for MySQli and mysqli_query. Thank you.
mysqli_query needs two parameters:
Your database connection
A query
That will result in this:
$result = mysqli_query($con, "SELECT image, caption FROM tbllinkcat, tblimages WHERE tbllinkcat.catid = tblimages.catid AND tbllinkcat.catid=1;");
You also have some weird looking quotation marks in your connect function, correct them:
$con = mysqli_connect("localhost", "my_user", "my_password", "my_db");
To fetch the array, you would use:
while($row = mysqli_fetch_assoc($result))
{
echo $row['image'];
echo "<br />";
echo $row['caption'];
echo "<br />";
}
And finally, to close the connection:
mysqli_close($con);
Note: Just so you know, when using queries with user input, please use prepared statements and bind_param. This will prevent SQL injection attacks. I will show and example below.
$stmt = $db->prepare("SELECT * FROM users WHERE username = ?");
$username = $_POST['username'];
$stmt->bind_param('s', $username);
$result = $stmt->execute();
<?php
$con = mysqli_connect("localhost”,“my_user","my_password”,"my_db”);
//establish database connection
if (!$con)
{
die('Could not connect:'.mysqli_error());
}
$result = mysqli_query($con,"SELECT image,caption FROM tbllinkcat, tblimages WHERE tbllinkcat.catid = tblimages.catid AND tbllinkcat.catid=1");
//perform sql select query with database connection
while($row = mysqli_fetch_array($result))
{
echo $row['image'];
echo "<br />";
echo $row['caption'];
echo "<br />";
}
mysqli_close($con);
?>
For More Info read :-https://www.php.net/manual/en/mysqli.query.php

Can't fetch data from database table.... 500 error

I have tried a ton of different versions of this code, from tons of different websites. I am entirely confused why this isn't working. Even copy and pasted code wont work. I am fairly new to PHP and MySQL, but have done a decent amount of HTML, CSS, and JS so I am not super new to code in general, but I am still a beginner
Here is what I have. I am trying to fetch data from a database to compare it to user entered data from the last page (essentially a login thing). I haven't even gotten to the comparison part yet because I can't fetch information, all I am getting is a 500 error code in chrome's debug window. I am completely clueless on this because everything I have read says this should be completely fine.
I'm completely worn out from this, it's been frustrating me to no end. Hopefully someone here can help. For the record, it connects just fine, its the minute I try to use the $sql variable that everything falls apart. I'm doing this on Godaddy hosting, if that means anything.
<?php
$servername = "localhost";
$username = "joemama198";
$pass = "Password";
$dbname = "EmployeeTimesheet";
// Create connection
$conn = mysqli_conect($servername, $username, $pass, $dbname);
// Check connection
if (mysqli_connect_errno) {
echo "Failed to connect to MySQL: " . mysqi_connect_error();
}
$sql = 'SELECT Name FROM Employee List';
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "Name: " . $row["Name"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
There be trouble here:
// Create connection
$conn = mysqli_conect($servername, $username, $pass, $dbname);
// Check connection
if (mysqli_connect_errno) {
echo "Failed to connect to MySQL: " . mysqi_connect_error();
}
There are three problems here:
mysqli_conect() instead of mysqli_connect() (note the double n in connect)
mysqli_connect_errno should be a function: mysqli_connect_errno()
mysqi_connect_error() instead of mysqli_connect_error() (note the l in mysqli)
The reason you're getting a 500 error is that you do not have debugging enabled. Please add the following to the very top of your script:
ini_set('display_errors', 'on');
error_reporting(E_ALL);
That should prevent a not-so-useful 500 error from appearing, and should instead show the actual reason for any other errors.
There might be a problem here:
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
If the query fails, $result will be false and you will get an error on the mysqli_num_rows() call. You should add a check between there:
$result = mysqli_query($conn, $sql);
if (!$result) {
die('Query failed because: ' . mysqli_error($conn));
}
if (mysqli_num_rows($result) > 0) {
The name of your database table in your select statement has a space in it. If that is intended try:
$sql = 'SELECT Name FROM `Employee List`';
i think you left blank space in your query.
$sql = 'SELECT Name FROM Employee List';
change to
$sql = "SELECT `Name` FROM `EmployeeList`";

Issues with PHP connection script to MSSQL database

Good morning,
I am quite new to php and I am trying to create a connection to a MSSQL server, I've been able to do it through MYSQL php connection but what I thought would be a simply change to MSSQL is proving to be much harder than expected.
The below code is basically what I am using after much googleing and search in this website this is what i've come up with:
<?php
$Server = "127.0.0.1";
$User = "BOB123";
$Pass = "BOBPASS";
$DB = "BOBDB";
//connection to the database
$dbconn = mssql_connect($Server, $User, $Pass)
or die("Couldn't connect to SQL Server on $Server");
//select a database to work with
$selected = mssql_select_db($DB, $dbconn)
or die("Couldn't open database $myDB");
//declare the SQL statement that will query the database
$query = "SELECT CustomerName from tblCustomer ";
//execute the SQL query and return records
$result = mssql_query($query);
$numRows = mssql_num_rows($result);
echo "<h1>" . $numRows . " Row" . ($numRows == 1 ? "" : "s") . " Returned </h1>";
//display the results
while($row = mssql_fetch_array($result))
{
echo "<br>" . $row["name"];
}
//close the connection
mssql_close($dbconn);
?>
As you can see the above script is very basic and there are very similar ones knocking around on the web could anyone help in connecting to the server this script doesn't seem to want to connect. I've changed the log on details as you'd probably know.
Thanks
Kris
You have a typo on:
$dbconn = mssql_connect($Server, $User, $Pass);
Should be:
$dbconn = mysql_connect($Server, $User, $Pass);
You're typing mysql wrong on each mysql_ function you create, change all mssql_ to mysql_
Note:
You shouldn't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. Learn about prepared statements instead, and use PDO or MySQLi.
#Daniel Gelling Doesn't look like a typo, looks like he is trying to connect to Microsoft SQL Server using mssql. You are correct about the API being outdated however.

why mysql_query not working?

Can someone help me figure out why mysql_query not working?
<?php
$dbhost = "localhost";
$dbusername = "USERNAME";
$dbpassword = "PASSWORD";
$dbname = "DB_NAME";
$connection = mysql_connect($dbhost, $dbusername,$dbpassword) or die('Could not connect');
$db_selected = mysql_select_db($dbname, $connection) or die(mysql_error());
echo " connect... \n";
$result = mysql_query("select * from test",$db_selected);
while($row = mysql_fetch_array($result))
{
echo $i++;
echo "Id : " . $row['Id'] . " Name : " .$row['name'] . " Address : " . $row['address'];
echo "<br>";
}
?>
result:
connect...
You must use $connection instead of $db_connected in your mysql_query. See the man page.
And the fact you did not see the error implies that you have error reporting not configured correctly; check your php.ini and this answer.
It wouldn't have worked anyway since you were fetching a numeric array instead of an associative array (use mysql_fetch_assoc() for that) which is needed by $rec['Id'] syntax (as opposed to $rec[3]).
However, if you are just now beginning with PHP and MySQL, do not use mysql_* functions. They are deprecated and will be soon removed, and you'll have wasted time learning something no longer in use. Use PDO instead. A teensy bit more difficult to master, but lightyears better.
If you want to reference the columns by name you must use mysql_fetch_assoc($result) not mysql_fetch_array($result))
But don't use either. use mysqli_* functions instead or better still pdo.
echo $i++ doesn't produce anything as it is undefined

PHP Can't Connect to MS SQL Express 2008

I'm struggling to connect to my MS SQL Express 2008 edition from my PHP files, but it seems virtually impossible.
I've found several guides/notes on teh intarweb solving the issues, but none of these have helped me any further.
I've taken a script from another site and entered my database information, but I still get errors:
<?php
$myServer = "localhost";
$myUser = "demo_basic";
$myPass = "1234";
$myDB = "demo_basic";
//connection to the database
$dbhandle = mssql_connect($myServer, $myUser, $myPass)
or die("Couldn't connect to SQL Server on $myServer");
//select a database to work with
$selected = mssql_select_db($myDB, $dbhandle)
or die("Couldn't open database $myDB");
//declare the SQL statement that will query the database
$query = "SELECT nitid, nisname ";
$query .= "FROM navitems";
//execute the SQL query and return records
$result = mssql_query($query);
$numRows = mssql_num_rows($result);
echo "<h1>" . $numRows . " Row" . ($numRows == 1 ? "" : "s") . " Returned </h1>";
//display the results
while($row = mssql_fetch_array($result))
{
echo "<li>" . $row["nitid"] . $row["nisname"] . "</li>";
}
//close the connection
mssql_close($dbhandle);
?>
I get this error:
Warning: mssql_connect()
[function.mssql-connect]: Unable to
connect to server: localhost in
C:\inetpub\vhosts\dexterholding.dk\httpdocs_rip\sql.php
on line 8 Couldn't connect to SQL
Server on localhost
You can see for yourself at: http://www.dehold.net/_rip/sql.php
Any ideas?
I'm running Windows Server 2008 with PLESK and PHP5 as FastCGI.
I found this guide which actually made it work for me:
http://samsami2u.wordpress.com/2008/06/30/how-to-connect-mssql-with-php/
With MSSQL, your server name will look like this: machinenameoraddress\serverinstancename
and example would be 192.168.14.201\MSSQLEXPRESS or TESTMACHINE\MYTESTDBSERVER.
It could be that the user account does not have permission to access SQL Server.
Although looking at your code you are using SQL auth and not Windows authentication, presumably this account is set up in SQL Server and it is configured to allow SQL Auth?

Categories