PHP function to perform SQL query not working - php

I am trying to use a function to perform an SQL query and return the result. Doing a manual SQL query with the same query as the below works and returns the correct result but doing it within PHP is not working at all (page is blank).
connection.php
<?php
require_once("settings.php");
$conn = oci_connect($db_user, $db_pass, $db_ip.'/'.$db);
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
?>
functions.php
<?php
require_once("connection.php");
function GetInvoice($n)
// returns invoice number for given order number
{
$stid = oci_parse($conn, 'SELECT InvoiceNo FROM Orders WHERE OrderNo = $n');
oci_define_by_name($stid, 'InvoiceNo', $InvoiceNo);
oci_execute($stid);
echo "$InvoiceNo";
}
GetInvoice(999645);
?>
Doing the manual SQL query shows a resulting InvoiceNo, it is just not working in PHP.
Thanks
Steve

You are trying to use a variable outside of function inside the function. That variable is not in function's scope. Due to this, $conn is undefined. Also, you have used $InvoiceNo withoud fetch result, I did some refoctoring on that place. You can use following;
function GetInvoice($n, $conn)
// returns invoice number for given order number
{
$stid = oci_parse($conn, 'SELECT InvoiceNo FROM Orders WHERE OrderNo = $n');
oci_define_by_name($stid, 'InvoiceNo', $InvoiceNo);
oci_execute($stid);
while (oci_fetch($stid)) {
echo "$InvoiceNo";
}
}
GetInvoice(999645, $conn);

The parameters you are passing in functions, seems undefined
as you have created your function needs only one parameter, then from where this will get this variable $InvoiceNo
oci_define_by_name($stid, 'InvoiceNo', $InvoiceNo);

Related

PHP SIMPLE DOM PDO select

I have in the database a list of links from which I want to take some data.
All the script is working, except the part when I'm taking the link from the DB and paste it in Simple DOM function.
"
include ('utile/db.php');
include_once('utile/simple_html_dom.php');
$dbh = new PDO("mysql:host=$servername;dbname=$dbname;charset=utf8;", $username, $password);
$sth = $dbh->query("SELECT link FROM pilots where year = '2007' and Contry ='CZ' and zboruri <> '101' limit 3 ");
foreach ($sth as $url) {
functie ($url['link']);
}
function functie($lin){
$linkul=file_get_html("$lin");
// pages number
$paging = $linkul->find('div[class*=paging]',0);
echo $paging;
$numar=-4;
foreach($paging->find('a') as $element=>$item){$numar++;}
echo $numar;
}
"
I receive the following error:
Fatal error: Call to a member function find() on null in C:\xampp\htdocs\para\teste.php on line 269
If I change the link manually it will work.
I think it is something related how I extract the link from DB and insert it the function.
Thank you
The issue with fetchALL in foreach.
The line changed:
foreach($sth->fetchAll() as $url){
The final code that is working:
include ('utile/db.php');
include_once('utile/simple_html_dom.php');
$dbh = new PDO("mysql:host=$servername;dbname=$dbname;charset=utf8;", $username, $password);
$sth = $dbh->query("SELECT link FROM pilots where zboruri > '101' limit 3");
foreach($sth->fetchAll() as $url){
functie ($url['link']);
}
function functie($lin){
var_dump($lin);
$linkul=file_get_html("$lin");
$paging = $linkul->find('div[class*=paging]',0);// pages number
echo $paging;
$numar=-4;
foreach($paging->find('a') as $element=>$item){$numar++;}
echo $numar;
}
Thank you for advices.
When I use PDO I use prepared statements, so the syntax on getting the result of the query is a little different... but I think that you need to fetch a row from your $sth since it would be a record set. Here's a snippit of what I do
$dbconn = new PDO('mysql:host='.$hostname.';port='.$dbPort.';dbname='.$dbName.';charset=utf8', $dbuser, $dbpass,array(PDO::MYSQL_ATTR_FOUND_ROWS => true));
$dbconn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$result=$dbconn->prepare($query);
$result->execute($arr);
if(!$result){
// do your error handling, result is either false
// for error or contains a recordset
$errorMessage=$dbconn->errorInfo();
}
$result->setFetchMode(PDO::FETCH_ASSOC);
while($row=$result->fetch()){
// do stuff here, $row is an associative array w/ the
//keys being the column titles in your db table
print_r($row);
}

unable to print oracle database query data in php

I want to print a value that taken from oracle database. but it is showing error.
Below is my code.
<?php
// Connects to the XE service (i.e. database) on the "localhost" machine
$conn = oci_connect('FUNREAD', 'clock24', '10.6.8.51:1525/DRFUNPD1');
if (!$conn)
{
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$atp1 = oci_parse($conn, 'select count(*) as count from ATP1.PENDING_MESSAGE');
oci_execute($atp1);
$atp1 = oci_fetch_array($atp1);
echo $atp11;
?>
But I am not getting right output. Below output I am getting.
Resource id #4
You're trying to echo a resource result, where what you need to do is to either retrieve the first row and output that, or loop over the results and output them:
while ($row = oci_fetch_array($atp1)) {
print_r($row);
}
Note that fundamentally it's probably a good idea not to re-use the $atp1 variable for both the query and the result set, use something more descriptive, e.g.:
$query = oci_parse($conn, 'select count(*) as count from ATP1.PENDING_MESSAGE');
oci_execute($query);
while ($row = oci_fetch_array($query)) {
print_r($row);
}
I'm pretty much copying this straight out of the manual (since I haven't used Oracle functions in PHP before)...

Php Autocomplete with Oracle error

I'm trying to use Auto-complete using Oracle.
I'd done this using MySQL, but with Oracle I got blank spaces.
This my MySQL Code.
global $db;
$term = trim(strip_tags(strtoupper($_GET['term'])));//retrieve the search term that autocomplete sends
$sql = "SELECT partNo as value FROM products WHERE partno LIKE '".$term."%' ORDER BY partNo LIMIT 15";
Basic::EventLog('getPartNosFromDB-> '.$sql);
$res =& $db->query($sql);
while ($row=$res->fetchRow()){
$row['value']=htmlentities(stripslashes($row['value']));
$row_set[] = $row;//build an array
}
echo json_encode($row_set);
And this is Oracle
$term = trim(strip_tags(strtoupper($_GET['term'])));//retrieve the search term that autocomplete sends
$conn = oci_connect('XXXX', 'XXXXX', 'XXXXX');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$sql = "SELECT product_definition as value FROM t_wip_job WHERE product_definition LIKE '".$term."%' AND ROWNUM < 16";
Basic::EventLog('getPartNosFromDB-> '.$sql);
$res = oci_parse($conn, $sql);
oci_execute($res);
while ($rowcc = oci_fetch_array($res, OCI_ASSOC)){
$row_set[] = $rowcc;//build an array
}
echo json_encode($row_set);
If I execute these query the first returns -> [{"value":"A2C00000000"},{"value":"A2C00000001"}] (MySQL)
And the second returns -> [{"VALUE":"A2C87115000"},{"VALUE":"A2C87114900"}] (Oracle)
But inside textbox when it tries to auto-complete the MySql result shows "A2C87115000" and "A2C87114900"
and the Oracle result shows " " and " ".
The problem could be with the case of the hash keys, since the MySql hash keys are lowercase ("value"), while the Oracle ones are uppercase ("VALUE").
When you load the json, since javascript is case sensitive, looking for "value" it finds the content only in the first case.
Try having lowercase keys in both case. This should do the trick!

Querying database with php

I am trying to query my database using php, to then display the results of the query. For this example, I only want the number of elements in my MySQL database.
My code is:
<?php
print("This is just a test");
print("This is another test");
// Create connection
$con=mysqli_connect("mysql.netsons.com","****","****","****");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
print("A third test");
$result = mysqli_query($con, "SELECT COUNT(*) FROM MyGames");
echo $result;
echo mysqli_fetch_array($result);
print("A forth test");
mysqli_close($con);
?>
This is the result:
This is just a testThis is another testA third test
What am I doing wrong?
mysql_fetch_array fetches ... an array.
$row = mysqli_fetch_array($result);
echo $row["COUNT(*)"];
I think it would be better to alias that column too:
SELECT COUNT(*) AS count FROM MyGames
...
echo $row['count'];
I would recomend using a diferent method of querying that is much safer(As far as I know there is no SQL Injection to worry about) and it saves a lot of time and space.
First you need to create an mysqli object
$stateConnect = new mysqli("localhost", "root", "PASS", "DBTable");
This does the same thing as mysqli_connect and mysqli_select_db
Then you want to define your SQL query
$sql = "SELECT `userVotes` FROM `users` WHERE `userEmail`=?";
Next you want to create a variable called a statement with your SQL "attached to it"
$statement = $stateConnect->prepare($sql);
Notice how in my SQL I didn't directly put the value required for userEmail, instead I put an '?'. This acts as a variable that we will later define(However it will always be a '?'
To define this variable we need to use.
$statement->bind_param('s', $SESSION['email']);
This binds $SESSION['email'] to the first qustion mark, the s is saying that the first question mark will be a string. Lets say we had to varribles:
$sql = "SELECT `userVotes` FROM `users` WHERE `userEmail`=? AND `userName`=?";
We would then use:
$statement->bind_param('ss', $SESSION['email'], "USERNAME");
Each s replresents a question mark and each value after that represents a question mark.
Now we have to execute our query with.
$statement->execute();
If we are expecting a result to be returned then we have to use
$statement->bind_result($userVotesText);
To bind the results to a variable, If I was expecting to columns of results I would need to put a second variable in.
Now to set those varribles we need to use
if($statement->fetch()){
$userVotesResult = userVotesText;
}
This method is much better than other for querying databases and is called Prepared Statement

Using the same mysqli connection ($conn=mysqli_connect) multiple times gives errors

I am using the mysqli functions (mysqli_connect, mysqli_select_db, mysqli_query) to call 1 select query and 2 stored procedures.
It seems that when I am using the same $connection (returned by mysqli_connect) multiple times, I am getting the following error message: "Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in..."
Below is my code:
<?php
$server="localhost";
$user="user";
$pass="pass";
$db="db";
$connection=mysqli_connect("$server","$user","$pass");
mysqli_select_db($connection, "$db") or die('Unable to select database.');
//First SELECT using $connection
$query=mysqli_query($connection, "SELECT item_name FROM items ORDER BY item_name DESC");
While ($result=mysqli_fetch_array($query,MYSQL_NUM))
{
$complete_result[] = $result[0];
$total_rows = $total_rows + 1;
}
//CALL to first sp using $connection
$query2 = mysqli_query($connection, "CALL sp_check_edits_remaining()");
while ($row2 = mysqli_fetch_array($query2, MYSQL_ASSOC)) {
$edits_remaining = $row2['edits_remaining'];
} // End while
//CALL to second sp using $connection
$query3 = mysqli_query($connection, "CALL sp_edit_data");
while ($row3 = mysqli_fetch_array($query3, MYSQL_ASSOC)) {);
$edits_id = $row3['id'];
} // End while
?>
Like I described, when I call the second sp, the above code gives me the error message mentioned above. (Please note that the connection is never closed.)
However, when I create another connection and provide it to the second sp call, this error disappears. This is shown in the code below
$connection2=mysqli_connect("$server","$user","$pass");
mysqli_select_db($connection2, "$db") or die('Unable to select database.');
//CALL to second sp using $connection
$query3 = mysqli_query($connection2, "CALL sp_edit_data");
while ($row3 = mysqli_fetch_array($query3, MYSQL_ASSOC)) {
$edits_id = $row3['id'];
} // End while
Can anyone please help me why this unexpected behavior?
Thanks and in advance!
It seems I have found a solution, which might be specific to my scenario.
My stored procs return only one row in the resultset.
So, after the CALL to the first sp and the corresponding while loop, I have simply added:
mysqli_next_result($connection);
This has removed the error message/warning I was receiving.
Anyone wants to comment whether this is the 'professional' approach?
You have an error somewhere, causing one of the mysql functions (probably the query call(s)) to return a boolean false, which you then blindly use in a fetch call. You need to add extra error handling, e.g.
$query = mysqli_query($connection, "...") or die(mysqli_error($connection));
never assume a query has succeeded.
enter code hereafter the query is finished, you must close the $connection then for another query, connect and assign the $connection again.
mysqli_close($connection);
$connection=mysqli_connect(bla,bla,bla,bla).

Categories