mysql_query function in php - php

<?php
$con= mysql_connect("localhost","root","mysql");
mysql_select_db("Db_name",$con);
$res=mysql_query("select *from table_name");
mysql_close($con); // closing connection before fetching contents.
while($r=mysql_fetch_array($res)) {
echo $r['ename'];
}
?>
This programs works even if i close the connection before fetching contents from the table.
In order get table contents from the $res connection is not necessary ?
Is$res just a program variable ? If so what kind of data structure it is using(associative array ? )
In oracle we have implicit cursor and explicit cursor. Are there any equivalent things in mysql?
In the above program where cursors come into picture ?

$res in your case is a special type called a "Resource". Simply put it is a collection of the data returned which the mysql_fetch_* functions operate. As such, it can live beyond the connection. Check the documentation for more details.

The MySQL client library will fetch the whole result set before the call to mysql_query() returns which explains why your code works.
You can use mysql_unbuffered_query() to fetch the rows incrementally in which case you must keep the connection open.
Note that fetching the rows is handled inside the MySQL client code. $res is just an opaque ressource type that represents an internal resultset object (buffered or not). You can only operate on that ressource by passing it to other MySQL functions.

In order get table contents from the $res connection is not necessary ?
Why did not you try it and see?
Anyway, what is the reason to close connection manually?
Is $res just a program varible ? If so what kind of data structure it is using(associative array ?
Yes, it is a variable. You can see what is inside with var_dump($res);
In oracle we have implicit cursor and explicit cursor.Are there any equivalent things in mysql ?
In the above program where cursors come into picture ?
What exact task are you trying to solve?

As jason said $res is just like a normal variable of type Resource. This variable holds its value even after the mysql connection is closed as it has no connection with the mysql connection.

Related

Execute Oracle stored procedures with Symfony & doctrine

I am trying to execute an stored procedures inside an Oracle database :
x_pkg.get_xID
It require one input & will output a single string
I already tried several different options that I found in internet :
$val = 'DATABASE';
$result = new ResultSetMapping ();
$query = $entityManager -> createNativeQuery ("BEGIN x_pkg.get_xID(${val}, :cursor); END;", $result);
In this case I get error : ORA-01008: not all variables bound (500 Internal Server Error)
$query = $entityManager -> createNativeQuery ("CALL x_pkg.get_xID(:data)", $result);
$query -> setParameters (['data' => $val]);
In this case I get error : ORA-06553: PLS-306: wrong number or types of arguments in call to 'GET_XID' (500 Internal Server Error)
$query = $entityManager -> createNativeQuery ("CALL x_pkg.get_xID(${val})", $result);
In this case I get error : ORA-06576: not a valid function or procedure name (500 Internal Server Error)
Thank you for your help.
I can help you explain why you get these errors and then it might help you to find the solution to solve the problem,
And just keep it in mind, the Oracle database is a bit tricky and different than other community used database such as MySQL, it has it's own power and strict rules,
**I will explain the first case at the end.*
So, in your second case, you get that error because Oracle expect the OUT variable to be a part of your Call which is not the case in your code and because it is inside the procedure
In your third case, using ${val} is not valid even if it's valid for PHP itself, the Oracle database see it in other way, so this is not an option for you,
Now about the first case, you should make sure that your procedure is returning a cursor and not a variable, I think you should check it in your Oracle database and also in your next line of code where you execute your query (it's not posted here so I can't be sure about it), this is a tricky part of Oracle database, you should make sure what your procedure is returning to avoid the error,
And good luck :)

Error: Commands out of sync; you can't run this command now

I new there are lots of answer as well as accepted answers related to this question but none of them solve my problem. Still I am getting this error.
Procedures:
CREATE PROCEDURE getAllProducts()
BEGIN
SELECT * FROM products;
END //
CREATE PROCEDURE getAllCategories()
BEGIN
SELECT * FROM category;
END //
Connection & calling:
$link = mysql_connect($host,$username,$password) or die(mysql_error());
mysql_select_db($database, $link) or die(mysql_error());
$allProducts = mysql_query("CALL getAllProducts");
while($row = mysql_fetch_array($allProducts)) { }
$allCategory = mysql_query("CALL getAllCategories");
while($row = mysql_fetch_array($allCategory)) { }
I've even called mysql_free_result($allProducts) before executing the next query. But nothing happens.
mysql_get_client_info() return mysqlnd 5.0.5-dev - 081106 - $Revision: 1.3.2.27 $
I found that the problem only arises if I run two queries.
As the MySQL-Documentation for 'Commands out of sync' points out:
[...] It can also happen if you try to execute two queries that return data
without calling mysql_use_result() or mysql_store_result() in between.
The Documentation for mysql_use_result() says e.g.:
After invoking mysql_query() or mysql_real_query(), you must call
mysql_store_result() or mysql_use_result() for every statement that
successfully produces a result set (SELECT, SHOW, DESCRIBE, EXPLAIN,
CHECK TABLE, and so forth). You must also call mysql_free_result()
after you are done with the result set.
Basically you need to tell your client what it should do with the result.
Well, usually this error occurs because there are still results pending from the query. There are mysqli_store_result and mysqli_free_result functions available. Since you are using mysql and mysql extension does not have such functions, you can try closing the connection after executing the first procedure and establishing the connection again to execute next procedure. Though this is not the perfect solution, but it will work in your case.
mysql_close($connection);
$connection = mysql_connect("localhost","username","password");
You can also try
mysql_free_result($allProducts);
Stored procedures always return an extra result set with errors/warnings information. As such, your stored procedures return multiple result sets (the actual result set from your select query and the extra errors/warnings result set). Calling mysql_fetch_array in a loop you only saturate one of them, leaving the other still pending, causing the error you see.
I don't know how to fix it with vanilla mysql_ library, with mysqli_ you can issue mysqli_multi_query, and then only use the first result set. See the example in the docs.
It's not a fix per se, but if you insist on staying with mysql_* functions, and assuming that you actually want to work with more complicated stored procedures (i.e. that the ones you supplied are just a simplified example) - you can change the stored procedures code to write the resultset into a temporary table (e.g. tmp_getAllProducts) instead of returning it, and then SELECT from it in your PHP.
This is what worked for me a while back when I was stuck with mysql_* and couldn't upgrade...
This is a known limitation of the mysql extension. You must either not use more than one stored procedure per connection or upgrade to mysqli.
https://bugs.php.net/bug.php?id=39727

ODBC fetch results from stored procedure in PHP

I'm having a little trouble getting the results from a stored procedure call to an ODBC connection.
I'm not used to calling stored procedures through ODBC from PHP, and I find the documentation incomplete (or maybe i'm missing something).
The code below seems to be working. But I can't find a way to fetch the result from $result.
$connect = odbc_connect("dsn","user","password");
$statement = "storedprocedure('IN value','OUT value_1','OUT value_2')";
$result = odbc_exec ($connect,$statement);
odbc_close($connect);
If I echo $result; it passes me a "Ressource id#" so something seems to work. But I can't figure out the fetch part :)
Your call worked and odbc returned you a resource ref from which you then need to fetch the results themselves: http://php.net/manual/en/function.odbc-fetch-array.php

How to test for empty recordset

I'm using PHP ODBC library to connect to a MSSQL 2008 server (http://php.net/manual/en/ref.uodbc.php).
Some of my stored procedures do not return record sets (e.g. they just do an insert or update). I would like to be able to handle output gracefully in this situation. After the database call is made, the output is injected into an array which is returned to the application for processing. Here are the key parts of the code (excluding error handling etc):
$sql_result = odbc_exec($connection, $sql);
while ($row = odbc_fetch_array($sql_result)) {
$resultArray[$i] = $row;
$i++;
}
If $sql_result has executed successfully, but does not contain a record set (as it would following an insert or update) then odbc_fetch_array triggers this warning:
Warning: odbc_fetch_row(): No tuples available at this result index
Ideally, I'd like to test $sql_result first to see if it contains an empty record set, but every obvious attempt I've tried always leads to the same warning message.
Anyone got a neat way of checking to see if $sql_result is empty?
I don't think there is a simple way using the PHP odbc API. Usually you would use different functions to process statements that return values such as SELECT vs those like UPDATE that do not.
If this is a utility that runs arbitrary statements you could parse the statement.
This isn't an empty result set, it's no result set at all, you might be able to tell the difference by examining the result in a debugger or using var_dump.

Can't get PHP code to work

I have this code, mainly it is meant to create shorurls for my site. But I simply cannot get it to work. Do you see something wrong with it? Is it ok to run a while() inside another one?
$urloriginal = $nt['fecha']."/".$nt['titulolower'];
mysql_query("SET NAMES 'utf8'");
$shortcheck = mysql_query("SELECT * FROM shorturls WHERE urloriginal = '".$urloriginal."' LIMIT 1");
while($urlitem = mysql_fetch_array($shortcheck)) {
if($urlitem['urloriginal'] != "0") {
echo "http://neutronico.com/u/".$urlitem['id'];
} else {
mysql_close($shortcheck);
mysql_query("INSERT into shorturls (urloriginal) VALUES ('$urloriginal')")
or die(mysql_error());
$shortget = mysql_query("SELECT * FROM shorturls WHERE urloriginal = '".$urloriginal."' LIMIT 1");
while($urlitem2 = mysql_fetch_array($shortget)) {
echo "http://neutronico.com/u/".$urlitem['id'];
};
mysql_close($shortget);
};
};
Thank you very much.
The first problem I see is that you're calling mysql_close() mid-script on a result set. Remove the call:
mysql_close($shortcheck);
mysql_close() is intended to be called on a resource link -- the database connection. Not on a query result resource. It is called implicitly when the script exits, so you needn't call it at all unless you have specific memory requirements. I think you are intending to call mysql_free_result(), but again this is called implicitly and you needn't call it unless you need to manage memory.
Later, remove this call, as it is not closing a MySQL resource link.
mysql_close($shortget);
Yes, it's OK to nest while statements.
The main problem that I didn't spot at first is that you're closing your connection in the middle of the query, thus remove all mysql_close statements.
However, after you solve this, you'll face another problem, since you're using only one MySQL connection, the second query loses all results of the first query, so probably you stop at the first row, or the first time the else branch gets executed.
To make it work, you' can choose one of the two options:
use two MySQL connections, and specify which one to use with the $link_identifier parameter mysql_query ( string $query [, resource $link_identifier ] )
run the first query, save all results in an array and then run the other queries, so the queries don't overlap. Use this option only if your table isn't too big.
Michael also suggested to check that your $urloriginal has been sanitized with mysql_real_escape_string(), or you face a risk of SQL injection.

Categories