php delete query doesn't work - php

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>

Related

Insert into sql table with php from html form

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);

Issue updating a record with SQL / PHP

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?

php - form submit button doesn't work

I want to do simple CRUD operations. I created a form for this and I am doing data entry. but when I refresh the page it automatically registers itself. I tried to solve this logic error with the "isset" function, but it did not. where can the error be?
$ad = isset($_POST['ad']) ? $_POST['ad'] : '';
$soyad = isset($_POST['soyad']) ? $_POST['soyad'] : '';
$adres = isset($_POST['adres']) ? $_POST['adres'] : '';
$tur = isset($_POST['tur']) ? $_POST['tur'] : '';
if(isset($_POST["submit"])){
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// bağlantı özelliklerinden hata modunu aktifleştirdik
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO `kisiler` (`ad`, `soyad`, `adres`, `tur`) VALUES ('$ad', '$soyad', '$adres', '$tur')";
// use exec() because no results are returned
$conn->exec($sql);
echo "işte şimdi oldu";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
}
<html>
<body>
<form action="" method="POST">
<p>
Ad: <input type="text" name="ad"/>
Soyad: <input type="text" name="soyad"/>
Adres:<input type="text" name="adres"/>
Tur: <input type="text" name="tur"/>
<input type="submit"name="submit"/>
</p>
</form>
</body>

<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?> not working, but hard coded form name works fine

<?php
$dsn = '';
$user = '';
$password = '';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
<?php
require 'mysqli_connect.php';
if(isset($_POST['submit']) && !empty($_POST['submit'])){
$sth = $dbh->prepare('INSERT INTO test_table(comment) VALUES(?);');
$comment = $_POST['comment'];
$sth->execute(Array($comment));
}
?>
the code below will refresh the page, but not post to my database (nor will REQUEST_URI). If I put the actual php form name in place of the <?php echo htmlspecialchars($_SERVER['PHP_SELF']);?> it works fine. I have tried double quotes, single quotes, and everything in between. What's up with this not working?
<form action = "<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method = "post">
<p>Comment</p>
<textarea name= "comment" rows="6" cols="50"></textarea><br />
<input type="submit" name= "submit" value="submit" id = "submit">
</form>

PHP Error - Call to a member function execute() on a non-object

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";
}
?>

Categories