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
CodePudding user response:
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.