SQL Server stored procedure not working in PHP - php

I have a problem getting a SQL Server stored procedure to work using PHP. My code is below. The stored procedure is expecting an integer to be passed to it. The message that displays is "Stored procedure error". This shows the connection is working. I'm not sure what's wrong. Can someone help me out? Thanks.
$db_connection = sqlsrv_connect($servername, $connectOpts);
if($db_connection === false) {
echo ("Error connecting to the database.");
exit;
}
$sp_command = "EXEC usp_testsp #valint=?";
$sp_vals = array( array("3", SQLSRV_PARAM_IN));
$sp_execute = sqlsrv_query($db_connection, $sp_command, $sp_vals);
if($sp_execute === false) {echo('Stored procedure error');}
else {echo('Success');}
sqlsrv_close($db_connection);

I don't see anything wrong with your code so I think your problem might be in your database itself. I can think of two possibilities.
Your stored procedure is written incorrectly. If that's the case you should post the stored procedure here so we can look it over.
Your stored procedure security settings aren't correct. You need to set the security settings inside SQL Server Management Studio. Off hand, I can't remember the exact path to set the security settings but it's something like: Right click on usp_testsp - properties - security. Then set the stored procedure with the database login information.

Related

error in calling a mysql stored procedure from a php page

Using phpmyadmin, i created a mysql stored procedure called mySP(). After creating the SP, i noticed that the SP is located in the information_schema db under ROUTINE table. I can see it here. Now from within phpmyadmin, under my actual database if i use SQL tab and do a call to the procedure using:
CALL mySP();
it works as required. NO issues.
Now i am trying to extend this by having a php page call this SP.
my php code is like this:
<?php
include("include_db_connection.php");
$callSP_query = "CALL mySP()";
$callSP_result = mysqli_query($db_conn, $callSP_query)
or die('Connected to database, but StoredProc failed');
if(!$callSP_result)
{
echo "Error with StoredProc...";
}
else
{
echo "Succsess! Called Stored Proc..";
}
?>
Now on loading this page on the browser, i always get the 'Connected to database, but StoredProc failed' error meaning that connection to db was established successfully, but there is some problem with calling the SP.
what could be the problem? The SP was created successfully and even called successfully from within phpmyadmin. where is the php call going wrong?
thanks!
EDIT:
I just checked the error code using mysqli_error() and it says "PROCEDURE mySP does not exist"
this was an issue with my own code. actually, u dont have to reference or even look into the information_schema. your sp can be called with the above code, if your database connection details are correct :)

Pass variable data from PHP to shell_exec command

I have a script that clones tables on to uniquely named MySQL databases from a master sql dump file . Each account has their own database, but the table structure is the same for all accounts. My solution was to dump the master database table and then through PHP shell_exec, run the MySQL controller cmd (mysql) to populate the newly created database with default tables.
At Issue: The process works but only when I hard code the accounts unique database name in the master sql dump file.
However, "USE acct_dbID" line inside the master sql file needs to be dynamically set at runtime.
Here is the code:
include('.dbase_credentials'); //constants for connection object
//using PHP built in connection class mysqli
$mysqli = new mysqli(DB_HOST,DB_UNAME,DB_UPWORD,DB_NAME);
if ($mysqli->connect_errno){
echo "Failed to open database connection: ".$mysqli->connect_error;
exit();
}
$dbID=$varNum; //variable, number ID generated earlier in the account setup process
//create database, doesnt return a resultset, no need for object var here
if ($mysqli->query("CREATE DATABASE acct_".$dbID) === TRUE){
//if dbase was created, clone the tables
$res = shell_exec('mysql -u dbaseUser --password=`cat /path/to/pass` -e "source /path/to/master_tables.sql" acct_'.$dbID);
//provide some UI feedback, shell_exec returns null on failure
if ($res!=null){
echo "The tables were cloned!";
}else{
echo "The cloning process failed!";
}
}else{
echo "no database created.";
}
So again, master_tables.sql needs variable data passed it at runtime so the "USE acct_dbID" can be specific to each new account.
Any thoughts are appreciated.
rwhite35
knittl had the right direction for what I need to do. See the comment conversation above. Thanks knittl.
Here is the new code block using multi_query and file_get_contents.
if ($mysqli->query("CREATE DATABASE acct_".$dbID) === TRUE){
$acct="acct_".$dbID;
$query = "USE ".$acct.";";
$query .= file_get_contents('/path/to/master_table.sql');
$result=$mysqli->multi_query($query);
}
Now account can be variable and multi_query will run each query statement in the string. I probably lose some efficiency but gain the ability to clone tables for each new account. The only additional edit made was to the master_table.sql. I removed all the comments that the dump process adds.
Thanks,
rwhite35

Database connection problems in PHP/MySQL

When I run the script below with the added line,
$count = 1;
I get a value of 1 on the screen, but when I take that line out I don't get get anything at all. tried moving it above the $count=mysql_num_rows($result); and I still didn't get a value.
$sql="SELECT EMAIL FROM CUSTOMER WHERE email='$myemail' and password='$mypassword'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
$count = 1;
echo $count;
What am I doing wrong here? I have never used PHP until now. The error is:
Can't connect to local MySQL server through socket
'/var/run/mysqld/mysqld.sock' (2)
This means that your MySQL server socket (/var/run/mysqld/mysqld.sock) is either missing or corrupt.
It could also mean that MySQL service is not working right, try restarting in SSH using:
$ service mysqld restart
If it says the service is missing, then say:
$ service mysql restart
I would guess at an a error with your SQL query (var_dump($count); would return false in this case).
To check this, I would do 2 things:
After your query do if(!$result) echo mysql_error( ); - this will show you any errors that happen while talking to the database
To check your SQL is being formed correctly, create it in a variable (e.g. $sql = "SELECT email ...";) and echo it out.
EDIT: Ahh just seen the update - it's a connection issue. Check that your mysql_connect( ) has the right host, username & password. Otherwise it could be a problem on your system (e.g. firewall or similar)
EDIT 2: As has been rightly pointed out, mysql_connect details would cause a different connection error to the one you're seeing. I've had a quick Google for it, and this cropped up http://lists.mysql.com/mysql/204035. Not sure it'll be any use as I've not read it through, but it does describe some steps for the solving this problem on someone else's system.
When you can't connect successfully to the database, return value from mysql_query function ($result) would not be a valid value. so when you give it to mysql_num_rows function, it fails & returns FALSE value, which has no visual effect on output screen!

connecting to a database using HostMonster

I'm using HostMonster as my web host and I'm trying connect to a database I created using MySQL inside of HostMonster. In order to call that database in my website do I need to use PHP? Or is there a way to create a javascript OnClick function that can call the database. I'm not using ASP.Net so it's not quite as simple as I would like it. Just curious if the best solution is PHP, if so I guess I should go learn it.
what are you planning to do with the database, other than just 'calling it'? You will need some language like PHP to connect to the DB to retrieve, insert, update or delete data in the DB.
here is a code for connection MySQL from PHP using MYSQLI extension
<?php
$dba_host='localhost';
$dba_name='root';
$dba_pass='';
$dba_db='sn';
$con=mysqli_connect($dba_host,$dba_name,$dba_pass,$dba_db) or die('Connection Refused !');
$stmt=mysqli_prepare($con,"SELECT UID FROM Main");
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $value);
while(mysqli_stmt_fetch($stmt))
$result[] = $value;
mysqli_stmt_close($stmt);
mysqli_close($con);
?>
Your javascript onClick function is running on the client side (in the browser) and the database is running on the server-side. You will need a server-side language to get the information from the database and send it to the browser.
You do not HAVE to use PHP to connect to a MYSQL database. Also, you can't connect to your database using only client-side javascript (ie. an onClick() function). You need to use a server side language, PHP is one choice.
To connect to a MYSQL database on hostmonster using PHP you will need to know your credentials that use to log into phpMyAdmin from your cpanel. Once you have made the connection you can then select the MYSQL database that you created. Once the database is selected you can query it using the "mysql_query" function in PHP. The following code does all of that and stores the results of the MYSQL query in a PHP variable called $result.
<?php
$con = mysql_connect("www.yourdomain.com","phpMyAdmin_username","phpMyAdmin_password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("mysql_database_name", $con);
$query = "SELECT * FROM TableName"
$result = mysql_query($query);
?>
Now you've got the results of the query inside the PHP variable $result and you can use it anyway you like.
If you put this in your 'public_html' folder and named it 'index.php' or 'index.html' this would automatically be run when someone went to www.yourdomain.com.
You can find a great tutorial series on PHP here http://thenewboston.org/list.php?cat=11.

Can't access the SQLite database with MAMP and PHP

I have been learning how to program websites lately and the time has come for me to add a database. I have in fact already successfully created a MySQL database and interacted with it with PHP.
My problem is I can't seem to access a SQLite database file with it. I am using MAMP to host locally for now. Here is a snippet of the code I am using to access the db and find and print out a value stored on it.
<?php
$dbhandle = sqlite_open('/Applications/MAMP/db/sqlite/Users');
if ($dbhandle == false) die ('Unable to open database');
$dbquery = "SELECT * FROM usernames WHERE username=trevor";
$dbresult = sqlite_query($dbhandle, $dbquery);
echo sqlite_fetch_single($dbresult);
sqlite_close($dbhandle);
?>
As you have access to the database (your code doesn't die), I'd say there's got to be an error later ;-)
Looking at your SQL query, I see this :
SELECT * FROM usernames WHERE username=trevor
Are you sure you don't need to put quotes arround that string ?
Like this :
SELECT * FROM usernames WHERE username='trevor'
Also, notice that sqlite_fetch_single will only fetch the first row of your data -- which means you might need to use sqlite_fetch_array or sqlite_fetch_object if you want to access all the fields of your resulset.

Categories