Error in if/else statement MySQL [duplicate] - php

This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 7 years ago.
I need some help making an if/else statement work in mysql
The if statement works proper, but the else statement buggs. I browers tells me
"Parse error: syntax error, unexpected 'else' (T_ELSE) in /var/www/domane/public_html/app/save.php on line 48" - which is the else line
It's supposed to get the current value of the row, and then add it to the new value and update it
<?php
$dsn = "databasename";
$username="username";
$password="password";
try {
$conn = new PDO($dsn, $username, $password);
$conn ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "Connection failed: ".$e->getMessage();
}
//------------------------ Does the category already exist in dietTbl? -------------------------
$sql="SELECT COUNT(*) AS subjectcount FROM dietTbl WHERE day=CURDATE()";
try {
$st = $conn->prepare($sql);
$st->bindValue(":mainsubject",$mainSubject, PDO::PARAM_STR);
$st->execute();
$row=$st->fetch();
$subjectcount=$row["subjectcount"]; // if >0 the yes, the category already exists
} catch (PDOException $e) {
echo "Server Error - try again!".$e->getMessage();
};
//------------------------ If it dosn't, insert it into dietTbl -------------------------
if ($subjectcount==0) {
$sql="INSERT INTO dietTbl (day, vegetables, fullgrain, milk, water) values (:day, :vegetables, :fullgrain, :milk, :water)";
try {
$st = $conn->prepare($sql);
$st->bindValue(":day",$_POST["day"], PDO::PARAM_STR);
$st->bindValue(":vegetables",$_POST["vegetables"], PDO::PARAM_STR);
$st->bindValue(":fullgrain",$_POST["fullgrain"], PDO::PARAM_STR);
$st->bindValue(":milk",$_POST["milk"], PDO::PARAM_STR);
$st->bindValue(":water",$_POST["water"], PDO::PARAM_STR);
$st->execute();
} catch (PDOException $e) {
echo "Server Error - try again!".$e->getMessage();
}
};
//------------------------ If it already exists, update dietTbl -------------------------
else {
SELECT SUM(vegetables) AS totalvegetables, SUM(fullgrain) AS totalfullgrain, SUM(milk) AS totalmilk, SUM(water) AS totalwater FROM dietTbl
$sql="UPDATE INTO dietTbl (vegetables, fullgrain, milk, water) values (:vegetables+totalvegetables, :fullgrain+totalfullgrain, :milk+totalmilk, :water+totalwater)";
try {
$st = $conn->prepare($sql);
$st->bindValue(":vegetables",$_POST["vegetables"], PDO::PARAM_STR);
$st->bindValue(":fullgrain",$_POST["fullgrain"], PDO::PARAM_STR);
$st->bindValue(":milk",$_POST["milk"], PDO::PARAM_STR);
$st->bindValue(":water",$_POST["water"], PDO::PARAM_STR);
$st->execute();
} catch (PDOException $e) {
echo "Server Error - try again!".$e->getMessage();
}
};
echo "Information saved";
$conn=null; //Close database connection
?>

From this part of code:
};
//------------------------ If it already exists, update dietTbl ----------
else {
remove ";"

Related

Call to a member function bindParam() on boolean in PHP prepared statements [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 5 years ago.
so I'm trying my hand at PDO for a project after referring to w3schools but I keep getting this error
Call to a member function bindParam() on boolean
here's my code. I cannot figure out whats causing it
if (isset($data->title) && isset($data->content) && isset($data->lang) && isset($data->show_on_site)) {
$response = array();
try {
$sql = 'INSERT INTO newsposts
(heading, content, author, language,show_on_page)
VALUES (:title, :content,:author,:lang,:show_on_site)';
$stmt = $db->prepare($sql);
$stmt->bindParam(':title', $db->real_escape_string($data->title), PDO::PARAM_STR);
$stmt->bindParam(':content', $db->real_escape_string($data->content), PDO::PARAM_STR);
$stmt->bindParam(':author', $_SESSION['user_session'], PDO::PARAM_STR);
$stmt->bindParam(':lang', $db->real_escape_string($data->lang), PDO::PARAM_STR);
$stmt->bindParam(':show_on_site', $db->real_escape_string($data->show_on_site), PDO::PARAM_BOOL);
if ($stmt->execute()) {
header_status(200);
$response['status'] = 'Success';
$response['message'] = 'Post Inserted';
} else {
header_status(400);
$response['status'] = 'Error';
$response['message'] = 'Something went wrong';
}
echo json_encode($response);
} catch (exception $e) {
header_status(503);
$response['status'] = 'Error';
$response['message'] = $e->getMessage();
echo json_encode($response);
}
As documentation states:
If the database server cannot successfully prepare the statement,
PDO::prepare() returns FALSE or emits PDOException (depending on error
handling).
so try to set "error mode" in your $db object to "exception" with
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
and wrap prepare() call in "try-catch" block to figure out what's going wrong, like this
try {
$stmt = $db->prepare($sql);
} catch (PDOException $e) {
echo $e->getMessage();
}

getting error for mysql when i am using if else in there

getting error for mysql when i am using if else in there. i dont know what should i do and when i am using duplicate condition to update then it not woring i am not be able to find where is error
this is the error which is i am getting.
ERROR:SQLSTATE[HY093]: Invalid parameter number: parameter was not
defined
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt=$conn->prepare("SELECT uniqueid FROM hotelcarttemp WHERE uniqueid=:uniqueid");
$stmt->execute(array(':uniqueid'=>$uniqueid));
$count=$stmt1->rowCount();
echo "count-".$count;
if($count>0)
{
$sql = "UPDATE hotelcarttemp SET `hotelname`='".$hotelname."',`roomtype`='".$roomtype."',`checkin`='".$checkin."',`checkout`='".$checkout."',`Country`='".$Country."',`Destination`='".$Destination."',`price`='".$price."' WHERE uniqueid='".$uniqueid."'";
echo "sql- ".print_r($sql);
$stmt = $conn->prepare($sql);
// echo print_r($stmt);
$stmt->execute();
}
else
{
$sql = "INSERT INTO hotelcarttemp (timestamp, packageid, uniqueid, hotelname, roomtype, checkin, checkout, Country, Destination, hoteldetail, price)
VALUES ('"
.$timestamp."','"
.$packageid."','"
.$uniqueid."','"
.$hotelname."','"
.$roomtype."','"
.$checkin."','"
.$checkout."','"
.$Country."','"
.$Destination."','"
.addslashes($hoteldetail)."','"
.$price."'
)";
// echo "sql- ".print_r($sql);
$stmt = $conn->prepare($sql);
// echo print_r($stmt);
$stmt->execute();
}
}
catch(PDOException $e) {
echo 'ERROR:' . $e->getMessage();
} here
Your SELECT query where condition is WHERE uniqueid=:uniqueid
And you are binding username to it
$stmt->execute(array(':username'=>$uniqueid));//:username invalid parameter
Change this to
$stmt->execute(array(':uniqueid'=>$uniqueid));

How to catch exact sql error in php pdo statement

I am new to pdo as I am just moving into it from the traditional method of doing queries. Below is what I have wrote and it works. My concern now is that if there any error in any of the query either the select,insert or update they are all capture by that one catch but then I cant pin point exactly to the error. So will multiple try and catch be the right direction ?
try {
$dsn = 'mysql:dbname='.dbDatabase.';host='.dbHost;
$link = new PDO($dsn, dbUser, dbPassword );
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $pe) {
die("Could not connect to the database $dbname :" . $pe->getMessage());
}
$link->beginTransaction();
$rollBackStatus="False";
try
{
$selectQuery1 ="Select ......";
$selectQueryResult1 = $link->prepare($selectQuery1);
$selectQueryResult1->bindParam(':uname', $userName);
$selectQueryResult1->execute();
$n1=$selectQueryResult1->rowCount();
//echo "TEST : ".$n1;
if($n1==1)
{
$row1 = $selectQueryResult1->fetch();
$userID=$row1['userID'];
if($row1['up']==$up){
$insertQuery1 ="Insert .......... ".
$insertQueryResult1 = $link->prepare($insertQuery1);
$insertQueryResult1->bindParam(':uID', $userID);
$insertQueryResult1->bindParam(':uIP', $userIP);
if($insertQueryResult1->execute()){
}
else{
$rollBackStatus="True";
$link->rollback();
}
$updateQuery1 ="Update ........ ";
$updateQueryResult1 = $link->prepare($updateQuery1);
$updateQueryResult1->bindParam(':uID', $userID);
if($updateQueryResult1->execute()){
}
else{
$rollBackStatus="True";
$link->rollback();
}
}
}
catch(PDOException $pe)
{
$rollBackStatus="True";
die("Error in selectQuery1 :" . $pe->getMessage());
$link->rollback();
}
if($rollBackStatus=="False"){
$link->commit();
$link=null;
if($headerSent!="")
{
header($headerSent);
}
}
You can check any error after execute query with following method.
$selectQueryResult1->execute();
$arr = $selectQueryResult1->errorInfo();
print_r($arr);

I can not insert into MariaDB table with my PHP script [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 9 years ago.
Improve this question
I recently moved to MariaDB, because since MySQL 5.6 it has been failing a lot for me.
MariaDB works flawlessly but, in a new project, I cannot insert data to the database with a PHP script. I can only insert manually. I have made no changes from scripts working with MySQL.
The INSERT statement is:
INSERT INTO participantes (nome, curso, email, equipe) VALUES (:nome, :curso, :email, :equipe);
And the script which should be inserting is:
$stmt = $this->dbh->prepare($this->SQL_INSERT);
$nome = $participante->nome();
$curso = $participante->curso();
$email = $participante->email();
$equipe = $participante->equipe();
$stmt->bindParam(':nome', $nome);
$stmt->bindParam(':curso', $curso);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':equipe', $equipe);
$stmt->execute();
The "participante" functions return data to be used, with no problems. Everything is inside a try/catch block, which reports no exceptions.
My PDO class is as follows:
class Connection extends PDO {
private $dsn = 'mysql:host=localhost;port=3307;dbname=dacu';
private $usr = 'dacu';
private $pwd = 'my password';
public $handle = null;
function __construct() {
try {
if ($this->handle == null) {
$dbh = new PDO($this->dsn, $this->usr, $this->pwd);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->handle = $dbh;
return $this->handle;
}
}
catch (PDOException $e) {
throw new Exception('Não foi possível conectar-se ao banco de dados: ' . $e->getMessage());
}
catch (Exception $e) {
throw new Exception('Um erro não identificado ocorreu: ' . $e->getMessage());
}
}
}
And using controller->insert gives me:
Warning: PDO::prepare(): SQLSTATE[00000]: No error: PDO constructor was not called in C:\Webserver\Files\dacu\controller\EquipesController.php on line 25
I can post code on pastebin if necessary, just ask.
Check your connection, then try this way, its working fine:
//first you need a connection to mysql use this and replace the variables
try {
$dbh = new PDO('mysql:host=localhost;dbname='.$db_name.'', $user, $pass, array(
PDO::ATTR_PERSISTENT => true
));
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
//then do the insert variable
$sql = 'INSERT INTO encomendas (`nome`, `user`, `id`, `email`) ';
$sql .= 'VALUES (:nome, :curso, :email, :equipe )';
$query = $dbh->prepare($sql);
//bindParam with your own variables
$query->bindParam(':nome', $varDoNome, PDO::PARAM_STR);
$query->bindParam(':curso', $varDoCurso, PDO::PARAM_STR);
$query->bindParam(':email', $varDoEmail, PDO::PARAM_STR);
$query->bindParam(':equipe', $varDaequipe, PDO::PARAM_STR);
//execute query
$query->execute()
;

How to handle PDO exceptions [duplicate]

This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 7 years ago.
I'm trying to work with PDO class on php but I have some trouble to find the right way to handle errors, I've wrote this code:
<?php
// $connection alreay created on a class which works with similar UPDATE statements
// I've simply added here trim() and PDO::PARAM... data type
$id = 33;
$name = "Mario Bros.";
$url = "http://nintendo.com";
$country = "jp";
try {
$sql = "UPDATE table_users SET name = :name, url = :url, country = :country WHERE user_id = :user_id";
$statement = $connection->prepare ($sql);
$statement->bindParam (':user_id', trim($id), PDO::PARAM_INT);
$statement->bindParam (':name', trim($name), PDO::PARAM_STR);
$statement->bindParam (':url', trim($url), PDO::PARAM_STR);
$statement->bindParam (':country', trim($country), PDO::PARAM_STR, 2);
$status = $statement->execute ();
} catch (PDOException $e) {
print $e->getMessage ();
}
print $status; // it returns a null value, and no errors are reported
?>
this portion of code doesn't report errors, but it simply doesn't work, the var $status at the bottom, return a null value.
can someone help me to find where I'm wrong?
PDO won't throw exceptions unless you tell it to. Have you run:
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
on the PDO object?
You can add the attribute one time while you connect you mysql.
function connect($dsn, $user, $password){
try {
$dbh = new PDO($dsn, $user, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
exit;
}
}
Thanks

Categories