I am using procedure in php. There are two procedure. First procedure is calling but second procedure is not working. When I comment the first procedure then second is working.
I don't know the that two procedure are called at a time or not. please tell me the way. I am new for procedure. Please help me.
if(isset($_REQUEST['customer'])){
$customer_name = $_POST['customer_name'];
$lang = 'en';
$qry = mysql_query("call customer (NULL,'$customer_name','$lang')")
or mysql_error();//first procedure
$data = mysql_num_rows($qry);
if($data > 0){
$msg ="Customer already exists.";
}
else{
mysql_query("call insertCustomer(NULL,'$customer_name','','','',1,'','','','',#ret,#err_code)")
or mysql_error();//second procedure
$rs = mysql_query('SELECT #p_ret,#p_err_code')or mysql_error();
$data = mysql_fetch_array($rs);
echo $data['#p_err_code'];
echo $data['#p_ret'];
}
}
First of all you should not be using mysql but mysqli or PDO - mysql is deprecated and support for this will be withdrawn.
Secondly your question is not specific: the second procedure might not be called at all because if ($data > 0) returns true and in this case that would be ok.
Try to improve your code for debugging purposes - your calls to mysql_error() are pointless as the function returns error as a string or empty string if no error but you don't echo it out or assign it to any variables. Also would be good to save the result of mysql_query (mysqli_query rather) to a variable and then test if it worked or not.
Related
We have to execute an MSSQL stored procedure in order to insert a set of rows and return the result. The procedure is working perfectly as intended when executed inside the Microsoft SQL Server Management Studio. But it's not working when executed with sqlsrv_execute or sqlsrv_query in PHP. It's inserting only one row and returning no rows.
The Stored Procedure can be found Here
The PHP code is
//Here my SP required one argument. so i passed one argument. this #param and stored procedure argument name should be same(case sensitive)
$sql = " { call ResmaxCompareWithProduction ( ?,? ) } ";
$param1 = 'All';
$param2 = 'desk';
$params = array(array(&$param1, SQLSRV_PARAM_IN),array(&$param2, SQLSRV_PARAM_IN));
$stmt = sqlsrv_prepare($conn,$sql,$params);
if ($stmt===false) {
// handle error
print_r(sqlsrv_errors(),true);
}else{
if (sqlsrv_execute($stmt)===false) {
// handle error. This is where the error happens
print_r(sqlsrv_errors(),true);
}
else
{
$resultsetarr = array();
while($row = sqlsrv_fetch_array($stmt)){
$resultArray[] = $row;
}
print_r($resultArray);
// success! It never gets here, though.
}
}
I tried to var_dump the result the procedure returned and it output resource(4) of type (SQL Server Statement)
The sqlsrv_errors() returns NULL
sqlsrv_fetch_array returned boolean(false)
I even tried using sqlsrv_query instead of sqlsrv_prepare and sqlsrv_execute, but same result.
Could you guys help me figure out what the issue is and make the procedure run as intended.
I have code
$email = "jb#tlb.com";
$row = mysql_query("SELECT EXISTS(SELECT email FROM accounts WHERE email='".$email."');");
echo $row[0];
However, nothing is echoed.
This is strange because something is being returned because, later in the code I have a function that is CALLED:
if ( $row[0] == 0 ) { echo "Email address is available<br>";};
However: this is strange because when i put the SAME CODE into mySQL database command prompt:
It clearly returns 1 or TRUE.
The mysql_query is returning 0 when the same exact command in mysql command prompt returns 1. Further: I am unable to echo the result for debugging purposes.
EDIT: Please not, the regular mySQL command is returning this and ONLY this:
EDIT: Here is there entire database:
MySQL query gives you a ressource. After that you have to fetch the data with mysql_fetch_assoc or mysql_fetch_row or something else for example. But its better to use prepared statements with mysqli or PDO to get more security.
$email = "jb#tlb.com";
$res = mysql_query("SELECT EXISTS(SELECT email FROM accounts WHERE email='".myql_real_escape_string($email)."')");
$row = mysql_fetch_assoc($res);
echo $row['email'];
Answer to your question:
$email = "jb#tlb.com";
$res = mysql_query("SELECT email FROM accounts WHERE email='".mysql_real_escape_string($email)."')");
$numRows = mysql_num_rows($res);
if($rowRows > 0) {
echo "Record Available";
}
You need to actually retrieve the result set from the query. mysql_query() just returns a resource handle for a successful select. You then need to fetch the results using mysql_fetch_* class of functions. Alternatively, you can use mysql_num_rows() to determine the number of rows returned in the result set.
In this case it is really senseless to wrap your actual query into a subquery. Just run your select and determine the number of rows:
$email = "jb#tlb.com";
$result = mysql_query("SELECT email FROM accounts WHERE email='".$email . "'");
if($result) {
$row_count = mysql_num_rows($result);
echo $row_count;
}
Also, you should not be writing new code using mysql_* functions, as these are deprecated. I would suggest mysqli or PDO extensions instead.
You need to do something like
while ($r = mysql_fetch_assoc($row))
{
echo $r[0];
}
after that code.
Let me know.
i have written a basic stored procedure using mysql
DELIMITER //
CREATE PROCEDURE `sp_sel_test`()
BEGIN
SELECT * FROM category c;
END//
DELIMITER ;
now i m calling it from php
the php code is:
<?php
$txt = $_GET['id'];
$name = $_GET['name'];
$con = mysql_connect("localhost","four","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("fourthes_a", $con);
//$result = mysql_query("select * from new_c where name like %". $name ."% or c_name like %" . $name . "% order by name asc;");
$result = mysql_query("call sp_sel_test()");
if ($result === FALSE) {
die(mysql_error());
}
while($row = mysql_fetch_array($result))
{
echo $row['category_id'] . " " . $row['c_name'];
?>
<br />
<?php
}
mysql_close($con);
echo $txt;
?>
now its giving the error
PROCEDURE fourthes_a.sp_sel_test can't return a result set in the given context
mysql_query() returns false when the query fails. You didn't check if your sproc query succeeded, so most likely you're passing that boolean FALSE to the fetch function, which is rightfully complaining.
Rewrite your code like this, as a bare mininum, for proper error handling:
$res = mysql_query('call sp_sel_test()');
if ($res === FALSE) {
die(mysql_error());
}
Never ever assume a query succeeded. Even if the SQL syntax is perfect, there's far too many other reasons for a query to fail to NOT check if it worked.
You need to set client flags while connecting for using stored procedures with php. Use this:
mysql_connect($this->h,$this->u,$this->p,false,65536);
See MySQL Client Flags for more details. PHP MySQL does not allow you to run multiple statements in single query. To overcome this you must tell PHP to allow such queries by setting CLIENT_MULTI_STATEMENTS flag in your connection.
I know last answer was a year ago, but...
CREATE PROCEDURE sp_sel_test(OUT yourscalarvariable INT/TEXT...)
Statements that return a result set cannot be used within a stored function. This includes SELECT statements that do not use INTO to fetch column values into variables, SHOW statements, and other statements such as EXPLAIN. For statements that can be determined at function definition time to return a result set, a Not allowed to return a result set from a function error occurs (ER_SP_NO_RETSET_IN_FUNC). For statements that can be determined only at runtime to return a result set, a PROCEDURE %s can't return a result set in the given context error occurs (ER_SP_BADSELECT).
So, your select shoould be like this:
SELECT * FROM category **INTO** c;
http://www.cs.duke.edu/csl/docs/mysql-refman/stored-procedures.html
I have a a php page which updates a mySql database it works fine on my mac (localhost using mamp)
I made a check if its the connection but it appears to be that there is a connection
<?php require_once('connection.php'); ?>
<?php
$id = $_GET['id'];
$collumn = $_GET['collumn'];
$val = $_GET['val'];
// checking if there is a connection
if(!$connection){
echo "connectioned failed";
}
?>
<?php
$sqlUpdate = 'UPDATE plProducts.allPens SET '. "{$collumn}".' = '."'{$val}'".' WHERE allPens.prodId = '."'{$id}'".' LIMIT 1';
mysql_query($sqlUpdate);
// testing for errors
if ($sqlUpdate === false) {
// Checked this and echos NO errors.
echo "Query failed: " . mysql_error();
}
if (mysql_affected_rows() == 1) {
echo "updated";
} else {
echo "failed";
}?>
In the URL i pass in parameters and it looks like this: http://pathToSite.com/updateDB.php?id=17&collumn=prodid&val=4
Maybe this has to do with the hosting? isn' t this simple PHP mySql database updating? what can be wrong here?
Why on localhost it does work?
Why on live server it doesn't?
Let's start with troubleshooting your exact problem. Your query is failing for some reason. We can find out what that problem is by checking what comes back from mysql_query, and if it's boolean false, asking mysql_error what went wrong:
$sh = mysql_query($sqlUpdate);
if($sh === false) {
echo "Query failed: " . mysql_error();
exit;
}
You have other problems here. The largest is that your code suffers from an SQL Injection vulnerability. Let's say your script is called foo.php. If I request:
foo.php?collumn=prodId = NULL --
then your SQL will come out looking like:
UPDATE plProducts.allPens SET prodId = NULL -- = "" WHERE allPens.prodId = "" LIMIT 1
-- is an SQL comment.
I just managed to nuke all of the product IDs in your table.
The most effective way to stop SQL injection is to use prepared statements and placeholders. The "mysql" extension in PHP doesn't support them, so you'd also need to switch to either the must better mysqli extension, or the PDO extension.
Let's use a PDO prepared statement to make your query safe.
// Placeholders only work for *data*. We'll need to validate
// the column name another way. A list of columns that can be
// updated is very safe.
$safe_columns = array('a', 'b', 'c', 'd');
if(!in_array($collumn, $safe_columns))
die "Invalid column";
// Those question marks are the placeholders.
$sqlUpdate = "UPDATE plProducts.allPens SET $column = ? WHERE allPens.prodId = ? LIMIT 1";
$sh = $db->prepare($sqlUpdate);
// The entries in the array you pass to execute() are substituted
// into the query, replacing the placeholders.
$success = $sh->execute(array( $val, $id ));
// If PDO is configured to use warnings instead of exceptions, this will work.
// Otherwise, you'll need to worry about handling the exception...
if(!$success)
die "Oh no, it failed! MySQL says: " . join(' ', $db->errorInfo());
Most mysql functions return FALSE if they encounter an error. You should check for error conditions and if one occurs, output the error message. That will give you a better idea of where the problem occurred and what the nature of the problem is.
It's amazing how many programmers never check for error states, despite many examples in the PHP docs.
$link = mysql_connect(...);
if ($link === false) {
die(mysql_error());
}
$selected = mysql_select_db(...);
if ($selected === false) {
die(mysql_error());
}
$result = mysql_query(...);
if ($result === false) {
die(mysql_error());
}
Your call to mysql_query() is faulty; you're checking the contents of the variable you're passing in but the function call doesn't work that way. It returns a value which is what you should check. If the query failed, it returned false. If it returns data (like from a SELECT) it returns a resource handle. If it succeeds but doesn't return data (like from an INSERT) it returns true.
You also have some problems constructing your SQL. #Charles mentions SQL injection and suggests prepared statements. If you still want to construct a query string, then you need to use mysql_real_escape_string(). (But I would recommend you read up on the mysqli extension and use those functions instead.)
Secondly, you're concatenating strings with embedded substitution. This is silly. Do it this way instead:
$sqlUpdate = 'UPDATE plProducts.allPens SET '.$collumn.' = \''.$val.'\'
WHERE allPens.prodId = '.intval($id).' LIMIT 1';
If you must accept it in the querystring, you should also check that $collumn is set to a valid value before you use it. And emit and error page if it's not. Likewise, check that $id will turn into a number (use is_numeric()). All this is called defensive programming.
I have a stored procedure:
delimiter //
create procedure userlogin(in eml varchar(50))
begin
select * from users
where email = eml;
end//
delimiter ;
And the php:
$db = new mysqli("localhost","root","","houseDB");
$eml = "tsubi#gmail.com";
$sql = $db->query("CALL userlogin('$eml')");
$result = $sql->fetch_array();
The error that I get from the browser when I run the php script:
Fatal error: Call to a member function fetch_array() on a non-object...
I am using phpmyadmin version 3.2.4 and mysql client version 5.1.41.
You have to use mysqli_multi_query, not query. Check
http://us.php.net/manual/en/mysqli.multi-query.php , they have a good example
mysqli::query returns false if the query fails (instead of returning a result object or true). You need to test whether the result actually is an object:
$sql = $db->query("CALL userlogin('$eml')");
if (is_object($sql))
$result = $sql->fetch_array();
else
printf("Error: %s\n", $sql->error);
You will probably get an error message explaining why calling the stored procedure didn*t work out.