I am using the following PHP document below running on my linux server:
<?
/*
** Connect to database:
*/
// Connect to the database (host, username, password)
$con = sqlsrv_connect('XXXXXX','XXXXX','XXXXXX')
or die('Could not connect to the server!');
// Select a database:
mssql_select_db('Quotes_SQL')
or die('Could not select a database.');
// Example query: (TOP 10 equal LIMIT 0,10 in MySQL)
$SQL = "SELECT TOP 10 * FROM FederalStockCards ORDER BY ID ASC";
// Execute query:
$result = mssql_query($SQL)
or die('A error occured: ' . mysql_error());
// Get result count:
$Count = mssql_num_rows($result);
print "Showing $count rows:<hr/>\n\n";
// Fetch rows:
while ($Row = mssql_fetch_assoc($result)) {
print $Row['Fieldname'] . "\n";
}
mssql_close($con);
?>
But after executing the PHP file by visiting:
http://cinicraft.com/Silverman/mssql.php
I am receiving the following output:
\n\n"; // Fetch rows: while ($Row = mssql_fetch_assoc($result)) { print $Row['Fieldname'] . "\n"; } mssql_close($con); ?>
I'm not quite sure what to make of it, is this output being returned by the MSSQL server?
You have used sqlsrv_connect while connecting. And then used all mssql functions later on. There is a difference between the two of them as mentioned here: http://blogs.msdn.com/b/brian_swan/archive/2010/03/08/mssql-vs-sqlsrv-what-s-the-difference-part-1.aspx.
Use mssql_connect instead, stated at: http://php.net/manual/en/function.mssql-connect.php
Also, ensure that mssql driver is enabled
Related
I want to make an API that when you access it it will show result in text format of how many rows are on my database.
Database info:
Username: predator_db
DB Name: predator_db
Table Name: database
I tried a couple of codes and I could not get it to work.
Code tried:
<?php
$con = mysql_connect("localhost","predator_db","PASS");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("predator_db", $con);
$result = mysql_query("select count(1) FROM database");
$row = mysql_fetch_array($result);
$total = $row[0];
echo "Total rows: " . $total;
mysql_close($con);
?>
Response Of Code: "Total Rows: " < Does not show how many rows. Error Log:
[05-Feb-2015 23:44:58 UTC] PHP Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in /home/predator/public_html/api/resolver/number.php on line 2
[05-Feb-2015 23:44:58 UTC] PHP Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /home/predator/public_html/api/resolver/number.php on line 10
You're trying to fetch the results from database... not from your actual database of predator_db.
I'll do it with the basics, but please look into MySQLi prepared statements and/or PDO.
$link = mysqli_connect("localhost", "predator_db", "PASS", "predator_db");
$result = mysqli_query($link, "select COUNT(id) AS count FROM `database`");
// make sure it worked
if(!$result) {
die('Error: ' . mysqli_error($link));
} else {
$num_rows = mysqli_fetch_assoc($result);
// echo it
echo "Rows: " . $num_rows['count'];
}
First off, it's not a good idea to name a table after a reserved keyword like database. However, if you are going to go that route, you will always have to place the name in backticks ``. So, your query should be
$result = mysql_query("select count(1) FROM `database`");
Also, look into MYSQLi, as the old MySQL driver is deprecated.
<?php
$link = mysqli_connect("localhost", "DB_USER", "DB_PASS", "DB_NAME");
$result = mysqli_query($link, "select COUNT(*) AS count FROM DB_NAME.DB_TABLE");
if(!$result) {
die('Error: ' . mysqli_error($link));
} else {
$num_rows = mysqli_fetch_assoc($result);
echo "Rows: " . $num_rows['count'];
}
?>
I'm trying to count entries in a database based on 2 basic criteria. It is returning a blank result, even though there are results to be found. Anyone have any idea what I am doing wrong here? I have tried it so many different ways and they all return no result. (If I enter the query directly in phpmyadmin it returns a result.)
$sql = "SELECT count(*) as total_count from orderOption3Detail WHERE orderDate='$orderDate' AND studentID='$studentID'";
$numericalResult = mysql_query($sql, $con);
$row = mysql_fetch_object($numericalResult);
$totalOrders1 = $row->total_count;
echo "My orders:" . $totalOrders1;
As others stated, make sure you sanitize variables before they go into query.
$sql = "SELECT * FROM orderOption3Detail WHERE orderDate = '" . $orderDate . "' AND studentID = '" . $studentID . "'";
$sql_request_data = mysql_query($sql) or die(mysql_error());
$sql_request_data_count = mysql_num_rows($sql_request_data);
echo "Number of rows found: " . $sql_request_data_count;
That's all you need.
Edited: providing full code corrected:
$con=mysqli_connect($db_host,$db_user,$db_pass,$db_name); // Check connection
if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } //global option 1
$sql = "SELECT count(*) as total_count from orderOption3Detail WHERE orderDate='$orderDate' AND studentID='$studentID'";
//echo $sql;
$numericalResult = $con->query($sql);
$row = mysqli_fetch_object($numericalResult);
echo $row->total_count; //echo (int) $row->total_count;
Please test this and let me know. Good luck!
----- End Editing ----
Have you tested assigning values directly as a test in your SQL string, like:
$sql = "SELECT count(*) as total_count from orderOption3Detail WHERE orderDate='05/23/2012' AND studentID='17'";
Also, did you check if the date's format is correct, reading that $orderdate variable and testing it in PHPMyAdmin?
Did you read the $sql with values inserted and test in PHPMyAdmin and worked?
Also, check the connection to assure there is no problem there.
One more thing, sorry. You seem to be using the wrong syntax in your mysql_query statement. That way works for mysqli_query, and the parameters would be inverted. Try only:
$numericalResult = mysql_query($sql);
Provided you made the connection and database selection previously, like in:
$connection=mysql_connect($db_host, $db_username, $db_password);
if (!$connection)
{
$result=FALSE;
die('Error connecting to database: ' . mysql_error());
}
// Selects database
mysql_select_db($db_database, $connection);
Best wishes,
I am querying a CRM2008 database on an MS server from an apache server.
I am trying to get the contactid from a view I have created on the DB.
I return the result fine, but it's not ?encoded? the way I want it.
How can I convert the results from my query into something readable (by me and my code).
<?php
ini_set('mssql.charset', 'UTF-8');
//connect
$dbconn = mssql_connect($Server, $User, $Pass)
or die("Couldn't connect to SQL Server on $Server");
//select
$selected = mssql_select_db($DB)
or die("Couldn't open database $myDB");
$query = " select contactid from V_UserDetails where emailaddress1 =
'me#you.com' ";
$result = mssql_query($query);
//grab it
while ($row = mssql_fetch_array($result))
{
$user_custid = ($row['contactid']);
}
echo "<b>customer ID:</b> " . $user_custid . "<br />";
outputs:
customer ID: &<DŽ���h���"
rather than the required:
customer ID: 234554345jhg54j34hg54jhg43jh5g34jhg5jhg3jhg34jg
The field is a UniqueIdentifier. In the select query I changed it to
$query = " select CONVERT(VARCHAR(36), contactid) from V_UserDetails where emailaddress1 =
'me#you.com' ";
And this pulls it from the DB as expected! Sorted!
$data=iconv("UTF-8", "ISO-8859-9", $data);
ISO-8859-9// change
here is my db connection code and query code:
// Connecting, selecting database
$link = mysql_connect('MySQLA22.webcontrolcenter.com', 'shudson', '*******')
or die('Could not connect: ' . mysql_error());
mysql_select_db('henrybuilt') or die('Could not select database');
$sql = "SELECT ID, vcImageName FROM corp_images WHERE idPage = 6";
$query = mysql_query($sql) or die ("Error");
There is no 'or die' error upon connecting, selecting, or querying
There is no error_log file
The sql query executes if I run it in my sql browser
What is going on???
$sql = "SELECT ID, vcImageName FROM corp_images WHERE idPage = 6"
Its missing ;
$sql = "SELECT ID, vcImageName FROM corp_images WHERE idPage = 6";
It appears correct...try adding this adapted code from the manual to further debug and see what you learn:
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$query) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $sql;
die($message);
}
// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(), etc.
while ($row = mysql_fetch_assoc($query)) {
echo $row['ID'];
echo $row['vcImageName'];
}
I am very new to PHP and can't seem to use mySQL data at all from PHP. The SQL query I wrote works fine in phpMyAdmin when I run it in the SQL editor, but the most I am able to get from the code is the following from var_dump. Nothing else displays anything at all.
resource(3) of type (mysql result)
Any help at all would be greatly appreciated!!
<?php
ini_set(‘display_errors’,1);
error_reporting(E_ALL|E_STRICT);
$con = mysql_connect("localhost","XXXXXXXX","XXXXXXX");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("sharetrader", $con);
$sharelist = mysql_query("SELECT DISTINCT tblStocks.stockSymbol, tblShareData.lookupDate FROM tblStocks LEFT JOIN tblShareData ON tblShareData.tickerCode = tblStocks.stockSymbol ORDER BY tblShareData.lookupDate ASC LIMIT 0 , 30");
if (!$sharelist) {
die('Invalid query: ' . mysql_error());
}
var_dump($sharelist);
while ($row = mysql_fetch_array($sharelist)) {
echo $row['tblStocks.stockSymbol'];
}
mysql_close($con);
?>
I am very new to PHP
But you're making great progress - just missing some of the finer points.
try:
while ($row = mysql_fetch_array($sharelist)) {
var_dump($row);
}
...and it should be obvious what's happening.