I am very new to PHP. Apologies if this is an elementary question.
I am trying to update a record using PHP / SQL. I have googled this error, but am unable to determine the problem out of the context of my code:
An error occured: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
Here is my function:
function updateTeam($val) {
global $server, $db, $dbUser, $dbKey, $message;
try {
$conn = new PDO("mysql:host=" . $server . ";dbname=" . $db, $dbUser, $dbKey);
$conn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = $conn -> prepare("UPDATE Team SET teamName=:teamName, teamLogo=:teamLogo, WHERE teamID=" . $val);
$sql -> bindValue(":teamID", $_POST["teamID"]);
$sql -> bindValue(":teamName", $_POST["teamName"]);
$sql -> bindValue(":teamLogo", $_POST["teamLogo"]);
$result = $sql -> execute();
if ($result) {
$message = "Customer record was updated";
} else {
$message = "The Customer record was not updated";
}
}
catch(PDOException $e) {
echo "<div class='notification container'><p>An error occured: " . $e -> getMessage() . "</p></div>";
}
$conn = null;
}
if (isset($_POST["updateTeam"])) {
updateTeam($_POST["teamID"]);
}
and here is my markup:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<label>Team ID</label>
<input type="text" name="teamID" placeholder="9" value="<?php echo $teamID; ?>">
<label>Team name</label>
<input type="text" name="teamName" placeholder="Watson's Bay Warriors" value="<?php echo $teamName; ?>">
<label>Team logo (optional)</label>
<input type="text" name="teamLogo" placeholder="Blob" value="<?php echo $teamLogo; ?>">
<input type="submit" name="insertTeam" value="Add">
<input type="submit" name="getTeam" value="Get">
<input type="submit" name="updateTeam" value="Update">
<input type="submit" name="deleteTeam" value="Delete">
</form>
I have similar functions in place that allow me to add, get and delete and have no issues.
"UPDATE Team SET teamName=:teamName, teamLogo=:teamLogo WHERE teamID=:teamID")
Remove the comma before the WHERE clause
In your code:
$sql = $conn -> prepare("UPDATE Team SET teamName=:teamName, teamLogo=:teamLogo, WHERE teamID=" . $val);
$sql -> bindValue(":teamID", $_POST["teamID"]);
$sql -> bindValue(":teamName", $_POST["teamName"]);
$sql -> bindValue(":teamLogo", $_POST["teamLogo"]);
Why is teamID =" .$val but you bind the param teamID to a post value? Could that be the error?
Related
I am trying to insert into my table (courses) in my sql database. But when I run my code (by clicking submit) I get this error:
I am no longer getting an error, I get the message:
New course created successfully
But when I check the database, the course has not been added
This is my code:
<?php
if (isset($_POST['submit'])) {
try {
require "../config.php";
require "../common.php";
$connection = new PDO($dsn, $username, $password);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO course (courseName, cDescription, programID, programYear, credit)
VALUES (:courseName, :cDescription, :programID, :programYear, :credit)";
$courseName = $_POST['courseName'];
$cDescription = $_POST['cDescription'];
$programID = $_POST['programID'];
$programYear = $_POST['programYear'];
$credit = $_POST['credit'];
$statement = $connection->prepare($sql);
$statement->bindParam(':courseName', $courseName, PDO::PARAM_STR);
$statement->bindParam(':cDescription', $cDescription, PDO::PARAM_STR);
$statement->bindParam(':programID', $programID, PDO::PARAM_STR);
$statement->bindParam(':programYear', $programYear, PDO::PARAM_STR);
$statement->bindParam(':credit', $credit, PDO::PARAM_STR);
$connection->exec($statement);
echo "New course created successfully";
} catch(PDOException $error) {
echo $statement. "<br>" . $error->getMessage();
}
}
?>
<?php include "templates/header.php"; ?>
<h2>Add a course</h2>
<form method="post">
<label for="courseName">Course Name:</label>
<input type="text" name="courseName" id="courseName" required>
<label for="cDescription">Course Description:</label>
<input type="text" name="cDescription" id="cDescription" size="40" required>
<label for="programID">Program ID:</label>
<input type="number" name="programID" id="programID" required>
<label for="programYear">Program Year:</label>
<input type="number" name="programYear" id="programYear" required>
<label for="credit">credit:</label>
<input type="number" name="credit" id="credit" required>
<input type="submit" name="submit" value="Submit">
</form>
Back to home
<?php include "templates/footer.php"; ?>
To try and see what was wrong, I tried simplifying this to, which works
<?php
if (isset($_POST['submit'])) {
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "courseselector";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO course (courseName, cDescription, programID, programYear, credit)
VALUES ('courseName', 'cDescription', 1, 4, 1)";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
}
?>
<?php include "templates/header.php"; ?>
<h2>Add a course</h2>
<form method="post">
<input type="submit" name="submit" value="Submit">
</form>
Back to home
<?php include "templates/footer.php"; ?>
I was missing
$statement->execute();
Above
$connection->exec($statement);
I wrote this code to update entry in my sql table, but i don't what is wrong.
Here is my form
<form action="" method="POST">
<center>
Alumni_ID :
<input type="text" name="valueh">
<br>
<input type="text" name="name" placeholder="name">
<input type="text" name="phone" placeholder="contact details">
<input type="text" name="details" placeholder="details">
<input type="text" name="address" placeholder="address">
<input type="submit" value="update data">
</center>
</form>
And this is php page,
<?php if (isset($_POST['submit'])) {
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "tssolutions";
$ab = $_POST['name'];
$bc = $_POST['phone'];
$cd = $_POST['details'];
$de = $_POST['address'];
$posted = $_POST['valueh'];
//create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
//check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//echo "connected successfully";
$sql = " UPDATE phone SET name='".$ab."', phone='".$bc."', details='".$cd."', address='".$de."' WHERE name = '".$posted."' ";
if(mysqli_query($conn, $sql)) {
echo "<hr>";
echo "<h3 class='w3-center' style='text-color:black'>Record Successfully Updated</h3>";
} else {
echo "<hr>";
echo "<h3 class='w3-center' style='text-color:black'>Error While Updating, Try Again</h3>";
}
mysqli_close($conn);
} ?>
Both the code are on same page Update.php, i wish to send alumni_id so that i can update that record where alumni_id = name in table phone, and then send new values of the row .
You forgot to name the submit button
Instead of
<input type="submit" value="update data">
Try this
<input type="submit" name="submit" value="update data">
To debug your code you can echo your SQL statement
echo $sql = "UPDATE phone SET name='".$ab."', phone='".$bc."', details='".$cd."', address='".$de."' WHERE name = '".$posted."';
You can then see if you have correct syntax and your values are sent correctly
try this code, maybe this helps
$sql = " UPDATE phone SET `name` ='$ab', `phone` ='$bc', `details` ='$cd', `address`='$de' WHERE `name` = '$posted' ";
I'm trying to create a delete function starting from this link
<a href="videogamedatabaseadduserlist.php?function=delete&IndEMail='.$_POST['IndEMail'].'&IdGame='.$row['IdGame'].'">Elimina<a>'.'<BR>'
and this is the php it should interact with
if ($_GET['function']== 'delete'){
$conn = new PDO('mysql:host=localhost;dbname=videogamelist', 'root', 'root',array(PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION));
$sql = "delete from lists where IndEmail = :IndEmail and IdGame = :IdGame";
$res_prepare = $conn->prepare($sql);
$res_prepare->bindParam(':IdGame',$_GET['IdGame']);
$res_prepare->bindParam(':IndEmail',$_GET['IndEmail']);
$a=$res_prepare->execute();
echo "Gioco cancellato";
}
After many try and searching on this site i can't find the reason the query doesn't work.
i tested and it worked! if this doesn't work for you, check db or form
try {
$conn = new PDO("mysql:host=localhost;dbname=videogamelist", 'root', 'root');
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);;
$sql = "DELETE FROM lists WHERE IndEmail = :IndEmail AND IdGame = :IdGame";
$res_prepare = $conn->prepare($sql);
$res_prepare->bindParam(':IdGame', $_GET['IdGame'], PDO::PARAM_INT);
$res_prepare->bindParam(':IndEmail',$_GET['IndEmail'], PDO::PARAM_INT);
$res_prepare->execute();
echo "Deleted";
}
catch(PDOException $e)
{
echo $e->getMessage();
}
not sure where $row['IdGame'] is coming from so i'm using basic form just to test the code:
<form name="delete" action="test.php" method="get">
<input type="text" name="IdGame">
<input type="text" name="IndEmail">
<input type="submit" name="delete" value="delete" >
</form>
I wrote thte following piece of code:
<?php
$username = $_POST['user'];
$password = $_POST['pass'];
$db = new PDO ('mysql:host=localhost;dbname=ozdatabase;charset=utf8', 'root', '');
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->setAttribute(PDO::ATTR_ERRMODE, 'ERRMODE_EXCEPTION');
$stmt = $db->prepare("SELECT id, users FROM ozusers WHERE username=? AND password=?");
$stmt->execute(array($username, $password));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$id = $rows['id'];
$user = $rows['users'];
if ($id) {
print "Logged";
}
else {
print "not good";
}
?>
This is the HTML Form:
<form id='login' action='login.php' method='post' accept-charset='UTF-8'>
<fieldset >
<LEGEND>COMMUNICATION</LEGEND>
<input type='hidden' name='submitted' id='submitted' value='1' />
<label for='username' >UserName*:</label>
<input type='text' name='user' id='username' maxlength="50" />
<label for='password' >Password*:</label>
<input type='password' name='pass' id='password' maxlength="50">
<input type='submit' name='Submit' value='Submit' />
</fieldset>
</form>
I get an error when trying to login in the page and it's written:
"Fatal error: Call to a member function execute() on a non-object in.. On line 15"
Why is this happening? I followed best practice guide and it showed to use the "execute()" function exactly like that..
Thanks
ERRMODE_EXCEPTION is constant wrap off quotes from it
$db->setAttribute(PDO::ATTR_ERRMODE, ERRMODE_EXCEPTION);//Your code fails at this line
Wrap your database init in try catch to capture any connection failures.
try {
$db = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
Currently the db->prepare() is failing, returning false and therefor not allowing you to call execute on a non object.
<?php
//error_reporting(0);
$username = $_POST['user'];
$password = $_POST['pass'];
// Connecting, selecting database
$db = new PDO ('mysql:dbhost=localhost;dbname=ozdatabase;charset=utf8', 'root', '');
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->setAttribute(PDO::ATTR_ERRMODE, ERRMODE_EXCEPTION);
//first
$stmt = $db->prepare("SELECT id, users FROM ozusers WHERE username = :username AND password = :password");
$stmt->execute(array(':username'=>$username, ':password' => $password));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($rows AS $r) {
$id = $r['id'];
$user = $r['users'];
}
if ($id) {
print "Logged";
}
else {
print "not good";
}
?>
This might be a silly question but I am trying to call the same query to two different pages but once I call the second time, the link to the page would not work anymore. The way I have it setup at the moment is that all the pages in the app are on one file (index.php). I am linking to each page by using id (href="#page2"). If I call the same query, depending on the order of pages, only the "top" page, or in this case, Page 1 will work. I tried changing the variable names so that it would treat it as a different call but to no avail.
I am developing this app using Phonegap Build and it would be really helpful if ANYBODY can help.
Page 1
<div data-role="page" id="page1">
<form action="post-comment.php" method="POST">
<h3>COMMENT</h3>
<input type="text" name="name" placeholder="Name"><br />
<textarea name="comment" cols="50" rows="2" placeholder="Enter Comment"></textarea><br />
<input type="submit" value="comment" onClick="javascript.ajax_post()"></input><br />
</form>
<?php
$find_comments = mysql_query("SELECT * FROM COMMENTS");
while($row = mysql_fetch_assoc($find_comments))
{
$comment_name = $row['name'];
$comment = $row['comment'];
echo "$comment_name - $comment<br />" ;
}
?>
</div>
Page 2
<div data-role="page" id="page2">
<?php
$find_comments1 = mysql_query("SELECT * FROM COMMENTS");
while($row = mysql_fetch_assoc($find_comments1))
{
$comment_name1 = $row['name'];
$comment1 = $row['comment'];
echo "$comment_name1 - $comment1<br />" ;
}
?>
</div>
I suggest using PDO - DOC instead of mysql, I would do it this way :
Connect to your database :
$hostdb = "your_host";
$namedb = "db_name";
$userdb = "user_name";
$passdb = "pass";
$options = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING);
try {
$db = new PDO("mysql:host=$hostdb; dbname=$namedb; charset=utf8", $userdb, $passdb, $options);
return $db;
} catch (PDOException $e) {
$err = "DB Connection Error, because: ". $e->getMessage();
print $err;
}
Now you can use $db to connect to your database in your script and fetch comments :
<div data-role="page" id="page1">
<form action="post-comment.php" method="POST">
<h3>COMMENT</h3>
<input type="text" name="name" placeholder="Name"><br />
<textarea name="comment" cols="50" rows="2" placeholder="Enter Comment"></textarea><br />
<input type="submit" value="comment" onClick="javascript.ajax_post()"></input><br />
</form>
<?php
$find_comments ="SELECT * FROM COMMENTS";
$stmt = $db->prepare($find_comments);
if(!$stmt->execute()){
print "error";
} else {
$comments = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($comments as $comment) {
echo $comment['name']."</br>";
echo $comment['comment'] ;
}
$stmt->closeCursor(); // Close connection
}
?>
</div>
then in your Page2 just do the same as Page1. You can define the SQL statement as a global variable and re-use it in your second query. just make sure to use closeCursor(); to close your db connection.