PHP SQL query server error - php

I have a table as so:
TABLE click_count
(
count int(3)
);
which is currently an arbitrary number. I have this php script with an html button which should just increment the number by one. The SQL query works in php my admin but gets an error when it's ran on the page.
<?php
require("config.inc.php");
if(!empty($_POST)){
$query = "UPDATE click_count
SET count = count + :submit_1
";
$query_params_ = array(
'submit_1' => $_POST['count']
);
try {
// These two statements run the query against your database table.
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["message"] = "Database Error. Please Try Again!";
die(json_encode($response));
}
$response["message"] = "Vote Cast!";
echo json_encode($response);
} else {
?>
<form action="vote.php" method="post">
Count:<br />
<input type="number" name="submit_1" value="1" />
<br /><br />
<input type="submit" value="Cast Vote" />
</form>
<?php
}
?>

You have to change your array key to match the one in preparedStatement. Like this:
$query_params_ = array(':submit_1' => $_POST['count']);
Indeed, you are refering to $query_params in the execute() method, but you are defining $query_params_ (with underscore in the end).

count is a reserved keyword of mysql, see: http://dev.mysql.com/doc/refman/5.0/en/reserved-words.html
try to enclose it into accents, like this:
UPDATE click_count
SET `count` = `count` + :submit_1
";

Related

Mysql Keeps deleting the written ID but the ID Doesn't exist in Database

I have created a HTML form where you can delete the staff just by putting the ID which is directly connected to the database.
When I put the ID first time it will delete it if its existing but even if it doesnt exist it will still say that it just got deleted even though it was never there.
Here's the PHP part of it
<?php
if(isset($_POST['removeemployees']))
{
$error = "";
if(!isset($_POST['employeeID']))
{
$employeeID = "";
}
else
{
$employeeID = $_POST['employeeID'];
}
if(empty($employeeID))
{
// Empty Employee
$error .= "employeeID Cannot be Empty";
}
//echo "Your Firstname is : $firstname and last name is : $lastname";
if($error == "")
{
$sql = "DELETE FROM employees WHERE ID = $employeeID ";
$result = mysqli_query($con, $sql);
if(mysqli_affected_rows($result) > 1)
{
echo "Record Deleted";
}
else
{
echo "Error Deleting record:".mysqli_error($con);
}
}
else
{
echo $error;
}
}
?>
And here's the HTML part of it, which is simple and working okay.
<div class="removeemployee">
<h3> Remove Employees </h3>
<p>Employee ID</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<input type="text" name="employeeID"><br>
<br><input type="submit" name="removeemployees" value="Submit Information">
</form>
</div>
I' m trying to make it work like this: if the ID is existing you can delete it, if it's not existing it should say that this ID is not existing in database or something like that. At first I thought I have to collect all the data from Mysql then compare it with input ID and go from there but I'm not sure.
No rows to delete is not an error.
If there's an error, mysqli_execute() returns false, not a result object.
mysqli_execute() only returns a result object when the query is SELECT (or some other type that returns a result set); for modification queries it just returns true or false. The argument to mysqli_affected_rows() must be the connection, not the return value.
$sql = "DELETE FROM employees WHERE ID = ?";
$stmt = mysqli_prepare($con, $sql);
$stmt->bind_param("i", $employeeID);
$stmt->execute();
if(mysqli_affected_rows($con) > 1)
{
echo "Record Deleted";
}
else
{
echo "Employee ID does not exist";
}
I've also shown how to recode using a prepared statement to prevent SQL injection.

Saving items by multiple users in database

What am doing wrong ?
this might be the simple solution to all experts here, but i have tried all the ways and i dont know where is my mistake ?
The idea is to add and items through my page to my database and then i can check them as todo list or to buy list. As well is in future this will be toBuy/toDo list web application so whole family members add items and in the end of the day one refresh the page and get the whole items in the database fetched!
my codes are below:
TodoTobuy.php
<?php
include("includes/header.php");
include("./forms/fadd-items.php")
?>
<?php
try {
//Tiedot kantaan
/* var_dump($_POST); */
$data1['items'] = $_POST['givenItems'];
$data1['amount'] = $_POST['givenAmount'];
$STH = $DBH->prepare("INSERT INTO todoORtobuy (items, amount, id) VALUES (:items, :amount, :id);");
$STH->execute($data1);
$data4['id'] = $data1['id'];
$sql4 = "SELECT id FROM todoORtobuy where id =:id ORDER BY start DESC LIMIT 50";
$kysely4 = $DBH->prepare($sql4);
$kysely4->execute($data4);
$tulos2 = $kysely4->fetch();
$_SESSION["startDate"] = $tulos2[0];
} catch (PDOException $e) {
echo "Yhteysvirhe: " . $e->getMessage();
file_put_contents('log/DBErrors.txt', 'Connection: ' . $e->getMessage() . "\n", FILE_APPEND);
}
?>
My form
<fieldset>
<form method="post">
<p>
Items toDo \ toBuy:
<br /> <input type="text" name="givenItems" placeholder="Write what toDO\toBuy..." maxlength="100"/>
</p><p>
Amount needed:
<br /> <input type="text" name="givenAmount" placeholder="Write amount of what to buy..." maxlength="100"/>
</p>
<br /> <div>
<input type="submit" name="submitUser" value="Add" id="send" class="sendbutton"/>
</div>
</p>
</form>
</fieldset>
error i get is: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
I mean i kindda understand the error, but cant find the mistake! Thank you for helping in advance
$data1['items'] = $_POST['givenItems'];
$data1['amount'] = $_POST['givenAmount'];
$STH = $DBH->prepare("INSERT INTO todoORtobuy (items, amount) VALUES (:items, :amount);");
$STH->execute($data1);
In your code you are using 3 prepared values for your query but you only pass 2.
Also when inserting you don't need to insert the id, it should be set as auto-increment in your table and basically takes care of itself for each record you insert.
That how it worked i commented those in lower part, whichwas not needed.
thank you #pr1nc3
<?php
try {
//Tiedot kantaan
/* var_dump($_POST); */
$data1['items'] = $_POST['givenItems'];
$data1['amount'] = $_POST['givenAmount'];
$STH = $DBH->prepare("INSERT INTO todoORtobuy (items, amount) VALUES (:items, :amount);");
$STH->execute($data1);
/* $data1['id'] = $data1['id'];
$sql4 = "SELECT id FROM todoORtobuy where id =:id ORDER BY start DESC LIMIT 50"; */
/* $kysely4 = $DBH->prepare($sql4);
$kysely4->execute($data1);
$tulos2 = $kysely4->fetch();
*/
} catch (PDOException $e) {
echo "Yhteysvirhe: " . $e->getMessage();
file_put_contents('log/DBErrors.txt', 'Connection: ' . $e->getMessage() . "\n", FILE_APPEND);
}
?>

PHP PSQL Insert Error

I'm trying to create a web interface for a baseball database but when I enter information into the forms and press submit it always gets to 'an error occurred'.
Here's the webpage with the form.
<html>
<?php
$dbconn = pg_connect("dbname=mine user=mine password=mine");
if ($dbconn) {
echo "Connection established <br/>";
}
echo "Here are the current NL West Teams <br/>";
$result = pg_query($dbconn, "SELECT Name, Record FROM Teams");
if (!$result) {
echo "An error occurred.\n";
exit;
}
while ($row = pg_fetch_row($result)) {
echo "Team: $row[0] Record: $row[1]";
echo "<br />\n";
}
?>
<form action="InsertPP.php" method="post">
Name: <input type="text" name="name"><br>
Team: <input type="text" name="team"><br>
Number: <input type="text" name="number"><br>
Handed: <input type="text" name="Handed"><br>
Position: <input type="text" name="Position"><br>
<input type="submit">
</form>
</html>
And here is the Insert PHP script.
<html>
<body>
<?php
$dbconn = pg_connect("dbname=mine user=mine password=mine");
if ($dbconn) {
echo "Connection established <br/>";
}
$_first = $_POST["Handed"];
$_second = $_POST["Position"];
$_third = $_POST["name"];
$_fourth = $_POST["number"];
$_fifth = $_POST["team"];
$Query = pg_query(dbconn, "INSERT INTO PosPlayer VALUES('$_first', '$_second', '$_third', $_fourth, '$_fifth)'");
if (!$Query) {
echo "An error occurred.\n";
exit;
}
echo "Your Player has been added!";
?>
</body>
</html>
I input the same values into postgres and the forms, and the player was created directly in postgres, but some error occurred when input into the form. Any ideas?
EDIT: I fixed the missing $ in front of the dbconn. Still getting the 'An error occurred'.
Check the end of the INSERT statement. You have
'$_fifth)'"
where you should have
'$_fifth')"
i.e. the closing quote for the value should be inside the closing parenthesis, not outside it.
You really should be using a prepared statement for this instead of a dynamic query. The syntax would be something like this (using the PostgreSQL driver):
$sql = "INSERT INTO PosPlayer VALUES($1, $2, $3, $4, $5)";
$result = pg_prepare($dbconn, "", $sql);
$result = pg_execute($dbconn, "", array($_first, $_second, $_third, $_fourth, $_fifth));
This will automagically handle proper quoting, escaping and type-matching of the variables' values to prevent (among other things) possible SQL injection attacks. Note that $1, $2, &c. is the pg driver's syntax for bind variables.
Replace
$Query = pg_query(dbconn, "INSERT INTO PosPlayer VALUES('$_first', '$_second', '$_third', $_fourth, '$_fifth)'");
By
$Query = pg_query($dbconn, "INSERT INTO PosPlayer VALUES('$_first', '$_second', '$_third', $_fourth, '$_fifth)'");
$ sign was missing from dbconn. Other than that, there seems to be nothing wrong with the code.

Can't insert value in db

I have a strange thing over here. I'm trying to insert a value in my database but it's not working for some reason. I have this code:
PHP:
<input type='file' name='images[]' />
<input type="text" name="newproject_name" id="tags"/>
<input type='text' name='order[]' value='$b' />
$project = new Project();
$project->photo = $_FILES['images']['name'][$key];
$project->order = $_POST['order'][$key];
$projectnaam = $_POST['newproject_name'];
if($project->createProject($_DB)) {
echo "OK";
} else {
echo "NOT OK";
}
}
FUNCTION:
class Project {
public function createProject($db) {
$sql = "INSERT INTO tblProject (
project,
photo,
order) // If you remove this line, the function is working
VALUES(
'".$db->escape($this->project)."',
'".$db->escape($this->photo)."',
'".$db->escape($this->order)."' // If you remove this line, the function is working
)";
return $db->insert($sql);
}
}
Strange thing is, when I delete the order-lines, the function is working just fine. I really don't know what I'm doing wrong...
ORDER is a reserved word. If you use backticks around the column name you should be good:
$sql = "INSERT INTO tblProject (
`project`,
`photo`,
`order`)
VALUES(
'".$db->escape($this->project)."',
'".$db->escape($this->photo)."',
'".$db->escape($this->order)."'
)";
I suggest you change the order column name to position or display_order.

Why does PDO rowCount() return 0 after UPDATE a table without modifying the existing data?

I am reading a tutorial on how to insert and update data into a MySQL table using PHP, the code is listed below. My problem is when i click update but I have not modified any data, rowCount() returns 0 and breaks the code.
My question is, If I am simply updating the database with the same values that are in the database, why does rowCount() return zero? My thoughts were that even though it was the same data it would be inserted anyway and return a count of the updated rows? I am guessing that it check the data before it try's the update? Can anyone shed some light on this for me and suggest a workaround? I have been starring at the code for hours and have been unable to come up with anything, thanks.
<?php
require_once('../includes/connection.inc.php');
// initialize flags
$OK = false;
$done = false;
// create database connection
$conn = dbConnect('write', 'pdo');
if (isset($_GET['article_id']) && !$_POST) {
// prepare sql query
$sql = 'SELECT article_id, title, article FROM blog WHERE article_id = ?';
$stmt = $conn->prepare($sql);
// bind the results
$stmt->bindColumn(1, $article_id);
$stmt->bindColumn(2, $title);
$stmt->bindColumn(3, $article);
// execute query by passing array of variables
$OK = $stmt->execute(array($_GET['article_id']));
$stmt->fetch();
}
// if form has been submitted, update record
if (isset($_POST['update'])) {
//prepare update query
$sql = 'UPDATE blog SET title = ?, article = ? WHERE article_id = ?';
$stmt = $conn->prepare($sql);
// execute query by passing array of variables
$stmt->execute(array($_POST['title'], $_POST['article'], $_POST['article_id']));
$done = $stmt->rowCount();
}
// redirect page on sucess or if $_GET['article_id'] not defined
if ($done || !isset($_GET['article_id'])) {
header('Location: http://localhost/PHP_Solutions/admin/blog_list_pdo.php');
exit();
}
// store error message if query fails
if (isset($stmt) && !$OK && !$done) {
$error = $stmt->errorInfo();
if (isset($error[2])) {
$error = $error[2];
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Update Blog Entry</title>
<link href="../styles/admin.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1>Update Blog Entry</h1>
<p>List all entries </p>
<?php if (isset($error[2])) {
echo "<p class='warning'>Error: $error[2]</p>";
echo '<pre>';
print_r($_POST);
print_r($error);
echo '</pre>';
}
if ($article_id == 0) { ?>
<p class="warning">Invalid request: record does not exist.</p>
<?php } else { ?>
<form id="form1" method="post" action="">
<input name="article_id" type="hidden" value="<?php echo $article_id; ?>">
<p>
<label for="title">Title:</label>
<input name="title" type="text" class="widebox" id="title" value="<?php echo htmlentities($title, ENT_COMPAT, 'utf-8'); ?>">
</p>
<p>
<label for="article">Article:</label>
<textarea name="article" cols="60" rows="8" class="widebox" id="article"><?php echo htmlentities($article, ENT_COMPAT, 'utf-8'); ?></textarea>
</p>
<p>
<input type="submit" name="update" value="Update Entry" id="update">
</p>
</form>
<?php } ?>
</body>
</html>
My question is, If I am simply updating the database with the same values that are in the database, why does rowCount() return zero?
rowCount is counting the affected rows by a query. As you haven't changed anything, there are zero affected rows.
PDOStatement->rowCount — Returns the number of rows affected by the last SQL statement
It has nothing to do with PHP - it's just how MySQL works.
MySQL documentations says:
For UPDATE statements, the affected-rows value by default is the number of rows actually changed. If you specify the CLIENT_FOUND_ROWS flag to mysql_real_connect() when connecting to mysqld, the affected-rows value is the number of rows “found”; that is, matched by the WHERE clause.
When you're using the UPDATE statement, and you submit the same values that are in database, it will always return zero, because it doesn't affected any row.
A way to resolve this problem is:
$done = $stmt !== false ? true : false;
What i did?
I did that:
if($stmt !== false){
$done = true;
} else{
$done = false;
}
Because if rowCount() is zero, but $stmt has executed without errors, $stmt was executed, but didn't change anything.
It's how MySQL works and has nothing intrinsically to do with the PDO extension; performing a regular mysql query would produce the same results. There is a workaround I found using the mysql functions, although I'm not sure if you can do anything similar with a PDO object.
$q = 'UPDATE etc...';
$r = mysql_query($q, $con);
$info = mysql_info(); // Returns info about last query.
list($matches, $changed, $warnings) = sscanf($matched, "Rows matched: %d Changed: %d Warnings: %d");
if ($matches > 0) {} // etc
Hope this helps a little.

Categories