What am I doing wrong here?
$adapter = new Adapter(array(
'driver' => 'Pdo_Firebird',
'database' => 'localhost:c:/firebird/mydb.fdb',
'username' => 'SYSDBA',
'password' => 'mypass'
));
$sql = 'SELECT * USERS';
$statement = $adapter->createStatement($sql);
$result = $statement->execute();
if I check $result->count() I always get zero (0). However I know this query should produce results.
I get no errors.
ok, so it appears I am actually getting a result, even though $result->count = 0.
So I have to add the following lines after my code above;
$resultSet = new ResultSet;
$resultSet->initialize($result);
foreach ($resultSet as $row)
{
echo $row->LOGIN . '<BR>';
}
Feels a little long winded. Is this the best way to do it? I presume I should add some check to see if any results where returned. But I can't see the correct way to perform this check.
Related
I'm facing with problem executing Oracle Procedure from PhP. Actually, I am using Doctrine to execute it.
What is interesting is the fact of any other Queries can be executed/fetched, but procedures.
Below, you can find the codes I managed to use, this Select works wonderfully:
$connection = $this->getApplication()->getDataSourceManager()->getEntityConnection();
$stmt = $connection->prepare("SELECT SYSDATE FROM DUAL"); //or any other select works nice
$stmt->execute();
However, any procedure wont work, this is one of them:
$connection = $this->getApplication()->getDataSourceManager()->getEntityConnection();
$stmt = $connection->prepare("call prc_nutr_values('$cdfil', '$cdserice', '001', '0000000036', 'S', '$selectdt', '$selectdt')");
$stmt->execute();
The procedure above, doesn't surge any changes in DB. It doesn't his procedure
Error found!
The main problem was that PhP doesn't throw any error (I don't know why. However, I made the transaction in a different way, creating a clean new connection and it threw the error, as following:
$entitiesPath = realpath(__DIR__."/../src/");
$isDevMode = true;
$entity_metadata_config = \Doctrine\ORM\Tools\Setup::createAnnotationMetadataConfiguration(array($entitiesPath), $isDevMode);
$connection_params = array(
'driver' => 'oci8',
'user' => 'user',
'password' => 'pwd',
'host' => 'IP',
'port' => 'port',
'dbname' => 'ORCL',
);
$entity_manager = \Doctrine\ORM\EntityManager::create($connection_params, $entity_metadata_config);
$conn=$entity_manager->getConnection();
$sql ="CALL FUNCTION_NAME('$param1', '$param2', '$param3', '$param4', '$param5', $param6, $param7)";
$outputMeta = $conn->exec($sql);
Connecting through this way, I could receive the error detailed:
it was $param6 and $param7 (non-formatted dates)
to solve this...
I just replace $param6 and $param7 with TO_DATE('$param6', 'DATE-FORMAT') and TO_DATE('$param7', 'DATE-FORMAT')
where 'DATE-FORMAT' is the used date format ('MM/DD/YYYY', or other used date formats)
there. I'm migrating from mysql to PDO structure, and i had an issue when tryign a foreach statement, if i could get some help, would appreciate. the structure that doesn't work is:
foreach ($con -> query('SELECT MIN(LEAST(L1_RMS, L2_RMS, L3_RMS)) AS menor_valor FROM afunda_eleva') as $array_min_afund)
{
$intensidade_elevacao[] = $array_min_afund['menor_valor'];
}
where
$con is my variable to connect to the database. (working fine).
The error that i get when i run this is:
"Invalid argument supplied for foreach()"
The problem is that i've used this same structure some lines beyond this in the program and it worked. Does anyone know a possible reason for this to be happening? Thanks in advance!
EDIT
$result = ($con -> query('SELECT MIN(LEAST(L1_RMS, L2_RMS, L3_RMS)) AS menor_valor FROM afunda_eleva'));
while ($row = $result -> fetch_assoc())
{
$intensidade_elevacao[] = $row['menor_valor'];
}
Something you're going to want to do is get PDO to throw exceptions. They're much harder to miss than warnings and errors.
Here's the PDO constructor I use...
$con = new PDO('mysql:host=localhost;dbname=your_db_name;charset=utf8', 'username', 'password', array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC));
Now, assuming your query actually works, it's only going to return one row with one column so try the following
$stmt = $con->query('SELECT MIN(LEAST(L1_RMS, L2_RMS, L3_RMS)) AS menor_valor FROM afunda_eleva');
$menor_valor = $stmt->fetchColumn();
Something really weird is going on here. I have this method for mysqli query.
public function select($options) {
$default = array (
'table' => '',
'fields' => '*',
'condition' => '2',
'order' => '1',
'limit' => 50
);
$options = array_merge($default,$options);
$query = "SELECT {$options['fields']} FROM {$options['table']} WHERE {$options['condition']} ORDER BY {$options['order']} LIMIT {$options['limit']}";
if ($result = $this->conn->query($query)) {
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
} else {
printf("Query failed: %s\n", $mysqli->error);
exit;
}
}
Once the query get executed I get $rows and everything works like a charm. But then when I try to get specific key in array I get the "Query failed:" without specific message :S
$options = array(
'table' => 'settings',
'fields' => 'setting_wall_post,setting_status_tag,setting_photo,setting_like,setting_comment',
'limit' => '1',
'condition' => "setting_id = 6",
);
$check = $this->mysql->select($options);
print_r($check);
$check = $check[0];
if($check["setting_wall_post"]) //if I comment out this IF block it works :(
$this->scope["wall_post"] = "publish_stream";
Also I've tried to close mysqli connection and then I get
Warning: mysqli::query() [mysqli.query]: Couldn't fetch mysqli
this IF block is acting like it works with mysqli :S
So the question is, what is the issue here? Why can't I access to "setting_wall_post"? I guess that part is the problem since it works if I comment out that IF block.
Edit. What a silly I am, overlooked such a typo: $this->conn have to be used instead of undefined $mysqli.
That's why one should always have error reporting no less than E_ALL
The code you posted just cannot cause this kind of error.
Change your error reporting code to this one
} else {
throw new Exception($this->conn->error);
}
this way you will have a stack trace which will show the chain of calls, pointing to the place of code that caused particular error.
BTW, the whole function looks unusable and error prone to me. it is open to injection and require more code than a conventional SQL
After being advised that the old method of access a database were not correct. I have now started using the PDO object. I am setting up a simple query but I am not getting any results back. Any help or advise would be appreciated. It is not even printing the query back to me. Would turning on error messages help?
<?php
//print_r(PDO::getAvailableDrivers());
$config['db'] = array( //This is the config array with the database details
'host' => 'localhost',
'username' => 'root',
'password' => '',
'dbname' => 'website'
);
$db = new PDO('mysql:host=' . $config['db']['host'] . ';dbname' . $config['db']['dbname'], $config['db']['username'], $config['db']['password']); //Instanciate an PDO Object
$query = $db->query("SELECT 'articles'.'title' FROM 'articles'");//running a query from the database
print_r($query); //printing a query
//while ($row = $query->fetch(PDO::FETCH_ASSOC)){
// echo $row['title'], '<br>';
//}
I would recommend you read up on PDO and error handling and reporting.
http://php.net/manual/en/pdo.error-handling.php
and
http://php.net/manual/en/pdo.errorinfo.php
They should show you how to easily get proper errors from your sql query so you can see whats going wrong.
In you're case your query is wrong it should be $query = $db->query("SELECT title FROM articles");
No need to specify the tabl to pull from in your select param section and no need for single quotes. You should be using the back tick quote not single quote anyway `
PHP manual :
<?php
function getFruit($conn) {
$sql = 'SELECT name, color, calories FROM fruit ORDER BY name';
foreach ($conn->query($sql) as $row) {
print $row['name'] . "\t";
print $row['color'] . "\t";
print $row['calories'] . "\n";
}
}
?>
You don't need quotes on table or column names.
Why dont you prepare your statements first and then execute them?
$stmt = $db->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll();
Other people have asked this question, but mine is a little more specific.
I have this query:
$sql = "UPDATE table SET option=? WHERE number=?";
$q = $conn->prepare($sql);
$q->execute(array($option, $number));
$q->setFetchMode(PDO::FETCH_BOTH);
echo $q->rowCount();
If the WHERE number already exists and the SET option is same, $q->rowCount() equals 0
If the WHERE number doesnt exist and the row does not update, $q->rowCount() equals 0
How can I distinguish between these non-updates?
On recent PHP versions, it's controlled by the PDO::MYSQL_ATTR_FOUND_ROWS attribute.
When set to true, according to the doc, the effect is:
Return the number of found (matched) rows, not the number of changed rows.
Will be better check before if exists? I use a common function for this in my miniclass for manage PDO, but i dont know if is the best solution because make one query more...
function checkExistsInDatabase($id, $table, $where = null){
// Connect
$Database = Database::connect();
// Query
$sql = "SELECT id
FROM $table
WHERE id = :id $where
LIMIT 1";
$params = array(
':id' => array(
'value' => $id,
'type' => 'int'
)
);
$q = $Database->query($sql, $params);
// Ha encontrado algo?
$resultados = $Database->fetchArray($q);
if(count($resultados) === 1){
return true;
}else{
return false;
}
}
You can try using REPLACE which work's like insert but if the row already exists its first deleted and then inserted. This has overwork from mysql side
Add this:
$db = new PDO($dsn, $username, $password, array(PDO::MYSQL_ATTR_FOUND_ROWS => true));
to the first "try {" part of your databasefunctions.php file