I have a problem with my sqlsrv_query. I have made a simple insert and update thru my application..my system popup insert successful..but when I use mssql studio management (MSSQL 2008 R2) also used EMS SQL, there is no data in my table..i try to used back my query form my application and paste at my query editor at mssql studio management, it’s works, 1 row(s) affected. I don’t now what is actually happening. I am using PHP 5.3.22, driver php_sqlsrv_53_nts_vc9.dll. I have no problem with my db connection..please help me.
$serverName = "servername"; $connectionInfo = array( "Database"=>"databasename", "UID"=>"username", "PWD"=>"password"); $conn = sqlsrv_connect( $serverName, $connectionInfo);
function msexecDB($query, $conn){
$result = sqlsrv_query($conn, $query) or trigger_error("A SQL error has occurred.Your Query:---------" . $query . "---------"); return $result;
}
$insert_program = "INSERT INTO TB_PROGRAM (kod_program) VALUES ('$kod_program')";
$row_program = msexecDB($insert_program, $conn);
Check the value of $kod_program. It's possible you're inserting a blank string, which could have the appearance of having no record at all, yet would successfully run the query.
Related
Using PHP to display MSSQL data.
I have a 32 fields of data stored in an MSSQL database. I need to retrieve and display this information online in specific order that does not match the field order.
I currently have a solution but it is not the most efficient way of doing it. So i welcome assistance and advise on achieving a more efficient method.
Currently i create a function to call a single field of data for each field (thats 32 separate functions), then place each function inside a div in its correct order.
Here is my php function:
function field1() {
$serverName = "#"; //serverName\instanceName
$connectionInfo = array( "Database"=>"#", "UID"=>"#", "PWD"=>"#");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
// start of query function
$sql = "select field1 from [stats]";
$query = sqlsrv_query($conn,$sql);
if(sqlsrv_fetch($query) ===false)
echo "couldn't fetch data";
$result = sqlsrv_get_field( $query, 0);
echo "$result";
}
i am new to php so be kind on my lack of experience & knowledge :).
For some reason, the following code inside the query works in my MySQL command console, yet when I try to run it as a Query in PHP, something keeps going wrong and I'm not sure what. Here is the code I've done so far.
//2. Perform database query
$query = "SELECT skills.element_id, content_model_reference.element_id, element_name FROM skills, content_model_reference WHERE (skills.element_id = content_model_reference.element_id)";
$result = mysql_query($query);
//Tests if there was a query error
if(!$result){
die("Database query failed.");
}
Is there something preventing the code that worked in MySQL (The line with SELECT) from working, or is my syntax somehow wrong?
EDIT: So it's saying I didn't select a database. Yet I thought I had. Here is the code above it:
//1. Create a database connection
$dbhost = "host"; //Host: Can be either an IP address, or a domain (like google.com).
$dbuser = "user";//User: The user that is connecting to the database.
$dbpass = "pass";//Password: This is the password that the user is using.
$dbname = "db";//Name: This is the name of the database.
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);//The value, 'handle,' is the connection.
//Test if connection occurred. Die ends the program/php, and in this case, also prints a message
if(mysqli_connect_errno()){
die("Database connection failed: ".
mysqli_connect_error().
" (". mysqli_connect_errno() . ")"
);
}
Like I said, the error message I am getting is pertaining only to the query, the server is fine with my database connection.
You're using mysqli_* for the connection, but you're using mysql_* for the QUERY... don't think you can do that, has to be one or the other (MYSQLI_ preffered). Also the query should be:
$result = mysqli_query($connection,$query);
I try to set connection with my site and mssql database. I can connect to database, but i can't execute SQL queries. My code is
$connection = mssql_connect('jass8l1.database.windows.net', 'username', 'password');
if (!$connection){
print_r(mssql_get_last_message());
}else{
$res= mssql_query('SELECT * FROM [my_database].[dbo].[table]', $connection);
print_r(mssql_get_last_message());
$row = mssql_fetch_array($res);
echo $row[0];
}
This code shows error
Reference to database and/or server name in 'my_database.dbo.table' is not supported in this version of SQL Server.
But when I execute this query online, link MANAGE URL, this error does not occur.
How can I solve this problem? Maybe I need some additional driver is for PHP?
The error message cannot be more descriptive than it is!
You simply cannot use the 4-word-notation (i.e. [DB_NAME].[SCHEMA].[TABLE_NAME].[COLUMN]. With SQL Azure you shall always use the 3-word notation (i.e. [SCHEMA].[TABLE].[COLUMN]).
Something more for SQL Azure is that you have to explicitly set Database in your connection. You can not do USE [DB_NAME] in SQL Azure.
When using SQL Azure with PHP I recommend that you go through the How to: Connect to Windows Azure SQL Database from PHP.
You have to alter your connection to something like:
$serverName = "tcp:ProvideServerName.database.windows.net,1433";
$userName = 'ProvideUserName#ProvideServerName';
$userPassword = 'ProvidePassword';
$dbName = "TestDB";
$table = "tablePHP";
$connectionInfo = array("Database"=>$dbName, "UID"=>$userName, "PWD"=>$userPassword, "MultipleActiveResultSets"=>true);
sqlsrv_configure('WarningsReturnAsErrors', 0);
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if($conn === false)
{
FatalError("Failed to connect...");
}
Also, it is strongly recommended to use Microsoft's MS SQL driver and not the standard PHP provided MSSQL (also referred in the How To).
I'm trying to develop a solution for my company and my goal is to connect our web server (which is on php and there is a web site already running on it) to our CRM database ( which is on mssql and based on another server ). My first solution is to have a replica of this CRM database in web server and do synchronization on it daily or hourly because of security issues. But now I'm thinking about making a direct connection, do you think will that be possible and if it's possible what can be the security problems I may come across. Do anyone have an experience on this kind of problem?
Thanks
J
Connecting to remote database will be slow, but at least your data will be consistent. If speed is not everything, I suggest this method. Migrating data can be painful.
You may want to create secure (SSL) connection between the servers. For detailed information please ask your system administrator.
doing the synchronization daily should be discouraged because you will lose real time data reliability.
If you are using PHP version 5.1, it still supports php-mssql connection thru php_mssql.dll, just be sure to enable it on your PHP.ini
<?php
$serverName = "ServerName"; /// use remote server name here
$uid = "sqlusername";
$pwd = "sqlpassword";
$databaseName = "DBName";
$connectionInfo = array( "UID"=>$uid,
"PWD"=>$pwd,
"Database"=>$databaseName);
/* Connect using SQL Server Authentication. */
$conn = sqlsrv_connect( $serverName, $connectionInfo);
$tsql = "SELECT id, FirstName, LastName, Email FROM tblContact";
/* Execute the query. */
$stmt = sqlsrv_query( $conn, $tsql);
if ( $stmt )
{
echo "Statement executed.<br>\n";
}
else
{
echo "Error in statement execution.\n";
die( print_r( sqlsrv_errors(), true));
}
/* Iterate through the result set printing a row of data upon each iteration.*/
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC))
{
echo "Col1: ".$row[0]."\n";
echo "Col2: ".$row[1]."\n";
echo "Col3: ".$row[2]."<br>\n";
echo "-----------------<br>\n";
}
/* Free statement and connection resources. */
sqlsrv_free_stmt( $stmt);
sqlsrv_close( $conn);
?>
I am using flex builder 3 to insert into mysql database using php and everything is working perfectly in my localhost, the problem is when I deploy the project in the web server and run it, it connect to the database but i can't insert data ( it shows nothing when i insert data )
another stupid thing is in another piece of code for retrieving (select) data that works good on both my localhost and web server.
here is the php code:
<?php
$host = "******";
$user = "******";
$pass = "******";
$database = "******";
$linkID = mysql_connect($host, $user, $pass) or die("Could not connect to host.");
mysql_select_db($database, $linkID) or die("Could not find database.");
$nickname = $_POST['nickname'];
$steam = $_POST['steam'];
$c1 = $_POST['c1'];
$c2 = $_POST['c2'];
$c3 = $_POST['c3'];
$results = mysql_query("INSERT INTO `phantom`.`members` (`TF2_Nickname` ,`Steam_User_Name`,
`class1` ,`class2` ,`class3` ,`time`) VALUES ($nickname, $steam, $c1, $c2, $c3,NOW())");
?>
You need to declare the values as strings in your MySQL query as well:
"INSERT INTO `phantom`.`members` (`TF2_Nickname`, `Steam_User_Name`, `class1`, `class2`, `class3`, `time`)
VALUES ('$nickname', '$steam', '$c1', '$c2', '$c3', NOW())"
And you should also prepare them in some way to avoid that they are mistakenly treated as SQL command (see SQL Injection). PHP has the mysql_real_escape_string function to do that:
"INSERT INTO `phantom`.`members` (`TF2_Nickname`, `Steam_User_Name`, `class1`, `class2`, `class3`, `time`)
VALUES ('".mysql_real_escape_string($nickname)."', '".mysql_real_escape_string($steam)."', '".mysql_real_escape_string($c1)."', '".mysql_real_escape_string($c2)."', '".mysql_real_escape_string($c3)."', NOW())"
Insert into requires either user right or admin right. Check if by chance You didnt modify somewhere in the code these rights, e.g., You changed by hand the name of your admin... If it works the select it is because selecting doesnt need so many rights. Even non user status can retrieve info through select but insert needs special rights. You know your code so think about this difference