Good day!
I am working on building a dummy application form that inserts data to a mySQL database. When running the functions, I successfully insert the data into the database. However, when the functions worked successfully, I am getting an error SQLSTATE[HY000]: General error
I thought it was occurring within my database access function, but it seems to be connecting alright. Here is my db access function:
function connectToDB($params)
{
try
{
$conn = new PDO('mysql:host=localhost;dbname=test', 'root', '');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare($params['sql']);
$stmt->execute($params['bindParam']);
$results = array();
$results['rowCount'] = $stmt->rowCount();
if($results['rowCount'] == 1)
{
$results = $stmt->fetch(PDO::FETCH_ASSOC);
return $results;
} elseif($results['rowCount'] < 2) {
$results = $stmt->fetch(PDO::FETCH_ASSOC);
return $results;
} elseif($results['rowCount'] > 2) {
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $results;
} elseif($results['rowCount'] == 2) {
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $results;
}
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
return $params;
}
Is there something I am missing in my code or is there something that shouldn't be in my db access code? I hope to learn from this to apply it in the future while I'm still trying to learn/improve on my PHP along the way. I hope I did my best to explain my issue and I appreciate your time reading!
Thank you
You do not use fetchAll().
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
with insert queries. Removing this statement it should fix your problem. Remember every fetch and fetchAll from your code.
Related
I'm trying to create a system, where my website generates an unique code (current date + 5 random characters) and that code is transferred to a table in my database.
Before function generateNumber() can insert the unique code into the database, it has to check if the code already exist in the database.
If the code doesn't exist, my function works flawlessly. But the problem is when the code can already be found on the database, my website just doesn't do anything (it should just re-run the function).
function generateNumber()
{
global $conn;
$rand = strtoupper(substr(uniqid(sha1(time())),0,5));
$result = date("Ydm") . $rand;
$SQL = $conn->query("SELECT code FROM test WHERE code='$result'");
$c = $SQL->fetch(PDO::FETCH_ASSOC);
if ($c['code'] > 0) { // test if $result is already in the database
generateNumber();
} else {
$sql2 = "INSERT INTO test (code) VALUES (?)";
$stmt2 = $conn->prepare($sql2);
$stmt2->execute([$result]);
return $result;
}
}
try {
$conn = new PDO("sqlite:db"/*, $username, $password*/);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo generateNumber();
}
catch(PDOException $e) {
echo "Error:" . $e->getMessage();
}
$conn = null;
?>
There are no error messages in the console, but I suspect the problem is this part of the code:
if ($c['code'] > 0) { // test if $result is already in the database
generateNumber();
}
Any idea how I can write this function in a better way?
Solution :
if ($c['code'] > 0) { // test if $result is already in the database
// if the code exists in db the function return nothing
// because you are missing a return :
return generateNumber();
}
I'm moving PHP code from mysql to ms sql server.
This will execute my query:
$r = $db_conn->prepare($sql);
$r->execute();
Before I start processing, I need to count how many rows were returned.
old code:
$r->num_rows;
new code:
$rows = $r->fetchAll(PDO::FETCH_ASSOC);
$rcount = count($rows);
All good, but when I try to access values from 1st row I'm getting nothing...
try {
$row = $r->fetch(PDO::FETCH_ASSOC);
} catch (Exception $ex) {
return 0;
}
I need to repoint to 1st row in my recordset after doing the count, how can I do this without having to requery the database again?
I'm new to PHP, sorry for dumb and probably obvious question.
Thanks in advance.
There isn't a way in PDO to reset the pointer. You could execute the query again, but given that you've already fetched all the data with your call to fetchAll, that is wasteful. Instead, to access the data, simply loop over the $rows array e.g.
foreach ($rows as $row) {
// do something
}
Note that if you expect an exception on fetch, it is likely you might get one on fetchAll too, so you should wrap the call to fetchAll in a try/catch block:
try {
$rows = $r->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $ex) {
return 0;
}
One possible approach, if you use PHP Driver for SQL Server, is to use PDOStatement::rowCount and client-side cursor. With this type of cursor row count is available after a query is executed, but this type of cursor should be used for small (medium) result sets.
<?php
# Connection
$server = 'server\instance,port';
$database = 'master';
$uid = 'uid';
$pwd = 'pwd';
# PDO Connection
try {
# SQL authentication
$conn = new PDO("sqlsrv:server=$server;Database=$database", $uid, $pwd);
# Windows authentication
#$conn = new PDO("sqlsrv:server=$server;Database=$database");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch( PDOException $e ) {
die( "Error connecting to SQL Server".$e->getMessage());
}
# Client-side cursor
try {
$options = array(
PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL,
PDO::SQLSRV_ATTR_CURSOR_SCROLL_TYPE => PDO::SQLSRV_CURSOR_BUFFERED
);
$stmt = $conn->prepare("SELECT * FROM master.sys.server_principals", $options);
$stmt->execute();
echo 'Row count: '.$stmt->rowCount().'<br>';
while ($row = $stmt->fetch(PDO::FETCH_ASSOC) ){
echo 'Login name: '.$row['name'].'<br>';
}
} catch( PDOException $e ) {
die( "Error executing query".$e->getMessage() );
}
# End
$stmt = null;
$conn = null;
?>
I have a reasonably complicated stored procedure in MSSQL 2008 R2 that, in the end, results in a small table being returned. The PHP will be called from javascript and I want it to return the array as JSON to be used in table in the javascript.
I am using PHP to access it and, using the profiler, can see that I am calling the SP and passing the correct parameters to it.
My PHP looks like this:
try {
$dbh = new PDO("sqlsrv:Server=(local);Database=cddDispo");
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo json_encode("Error connecting to the server.");
die ();
}
$lot = $_POST["lot-input"];
$layerAdder = $_POST["layer-input"];
$adder = substr($layerAdder,-3,3);
$adder = str_replace('=','',$adder);
$layer = substr($layerAdder,0,strpos($layerAdder,' '));
$sth = $dbh->prepare('EXEC dbo.pullDispo ?,?,?');
$sth->bindParam(1,$lot,PDO::PARAM_STR);
$sth->bindParam(2,$layer,PDO::PARAM_STR);
$sth->bindParam(3,$adder,PDO::PARAM_STR);
$array = array();
try {
$sth->execute();
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
//I want to build my output array here
}
}catch (PDOException $e) {
echo "Error getting data, please try again.";
die();
}
header('Content-type: application/json');
echo json_encode($array);
This is the first time that I have tried to return table results from a stored procedure and even with several PHP Manual/ Google searches I have not figured out how to capture the table back in the PHP. I have a less elegant workaround (write the SP table to a static table and call that table later in the PHP) but would rather figure out if I can do in a more elegant manner. Any advice is much appreciated.
I thought it might be useful if I posted my final code:
function array_push_assoc($array,$key,$value) {
$array[$key] = $value;
return $array;
}
header('Content-type: application/json');
try {
$dbh = new PDO('sqlsrv:Server=(local);Database=cddDispo');
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo json_encode('Error connecting to the server.');
die ();
}
$lot = $_POST['lot'];
$layer = $_POST['layer'];
$adder = $_POST['adder'];
$sth = $dbh->prepare('EXEC dbo.pullDispo ?,?,?');
$sth->bindParam(1,$lot,PDO::PARAM_STR);
$sth->bindParam(2,$layer,PDO::PARAM_STR);
$sth->bindParam(3,$adder,PDO::PARAM_STR);
$results = array();
$combinedArray = array();
$array = array();
$count = 0;
try {
$sth->execute();
do {
$results[] = $sth->fetchAll(PDO::FETCH_ASSOC);
}while ($sth->nextRowset());
foreach($results as $row) {
if($count == 0) {
$headerArray =
[
'Lot' =>$row['Lot'],
'Layer' =>$row['Measured Layer'],
'Product' =>$row['MES Product'],
'Adder' =>$row['Adder Chart']
];
$combinedArray = array_push_assoc($combinedArray,'header',$headerArray);
}
$count++;
//This is for formatting of final table
if($row['UDL'] == 0) {
$udl = 'NA';
} else {
$udl = round($row['UDL'],4);
}
$infoArray =
[
'Wafer' =>$row['Wafer'],
'Type' =>$row['Type'],
'Count' =>$row['Count'],
'CDD' =>round($row['CDD'],3),
'UCL' =>round($row['UCL'],4)
];
array_push($array,$infoArray);
}
$combinedArray = array_push_assoc($combinedArray,'detail',$array);
}catch (PDOException $e) {
echo json_encode('Error running stored procedure.');
die();
}
echo json_encode($combinedArray);
Could it be that your stored procedure is returning multiple result sets? This includes output like warning messages or number of rows affected. Try adding SET ANSI_WARNINGS OFF or SET NOCOUNT ON at the top of your stored procedures after the AS. You can also try advancing to the next result set in PHP before trying to get the results by calling $stg->nextRowset() before $sth->fetchAll().
Use fetchAll() to get your resultset, then encode that array as your json response:
$array = array();
try {
if($sth->execute()){
$array = $sth->fetchAll(PDO::FETCH_ASSOC);
}else{
$array = array('error'=>'failed to execute()')
}
}catch (PDOException $e) {
echo "Error getting data, please try again.";
die();
}
header('Content-type: application/json');
echo json_encode($array);
When you are calling a stored procedure with multiple result sets, you probably do not want to add SET NOCOUNT ON into every procedure you have; you always can add
$dbh->setAttribute(constant('PDO::SQLSRV_ATTR_DIRECT_QUERY'), true);
$dbh->query("SET NOCOUNT ON");
before of
$dbh->prepare($query);
and it will work.
Getting no results no matter how broad my query
PHP: 5.3
Sqlite3: 3.6
PDO: 5.3.3
I would think this should be a very simple process but even looking around I still don't know why I'm getting 0 results. Here is my code:
<?php
$sqlite = new PDO('sqlite:/example.db');
$result = $sqlite->query('SELECT * from foo');
if(!$result)
{
echo 'fail';
return false;
}
?>
Any ideas on what I am doing wrong? The 'foo' table will only have four columns, and this test db only has one table. Running the query in sqlite displays the results fine.
You have to execute the statement first than fetch the result.
You might add try/catch block around the execute method call. and do some error handling.
Here's an example of catching an Exception. Do not use it as a design guideline.
<?php
try
{
$sqlite = new PDO('sqlite:/example.db');
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
$statement = $sqlite->prepare('SELECT * from foo');
try
{
$statement->execute();
}
catch(PDOException $e)
{
echo "Statement failed: " . $e->getMessage();
return false;
}
$result = $statement->fetchAll();
var_dump($result);
?>
I'm using PDO to grab records from a mysql table. The data will be encoded with json_encode() and printed through the Slim framework for the API:
$app->get('/get/profile/:id_user', function ($id_user) use ($app) {
$sql = 'SELECT * FROM user WHERE id_user = :id_user';
try {
$stmt = cnn()->prepare($sql);
$stmt->bindParam(':id_user', $id_user, PDO::PARAM_INT);
$stmt->execute();
$data = $stmt->fetch(PDO::FETCH_ASSOC); // THIS!!!
if($stmt->rowCount()) {
$app->etag(md5(serialize($data)));
echo json_encode($data,JSON_PRETTY_PRINT);
} else {
$app->notfound();
}
} catch(PDOException $e) {
echo $e->getMessage();
}
});
Should I use
$data = $stmt->fetch(PDO::FETCH_ASSOC);
or
$data = $stmt->fetchObject();
? Any direct benefits on fetching the data as an object? I've read some examples but they never explain why. The only usage for the resulting data will be to print it in JSON format. Thanks!
It doesn't matter. Though I'd cut an object out with Occam's razor.
Also your code is slightly wrong and redundant. Here is a proper version
$sql = 'SELECT * FROM user WHERE id_user = :id_user';
$stmt = cnn()->prepare($sql);
$stmt->bindParam(':id_user', $id_user, PDO::PARAM_INT);
$stmt->execute();
if ($data = $stmt->fetch()) {
$app->etag(md5(serialize($data)));
echo json_encode($data,JSON_PRETTY_PRINT);
} else {
$app->notfound();
}
there is no point in setting fetch mode for the every query when you can set it globally.
numrows() call is also useless.
and of course catching an exception is redundant, insecure and unreliable.