for admin panel i have made a table with delete, edit and add option with each row, every thing is working perfect except the execution of update query, uptil now have shown text to be edit in its form, and delivered the edit values to the next page which i have verified by usin echo(). My code is as following
update.php
<head>
<?php
// 1. Create a database connection
// 2. Select a database to use
include('connect.php');
?>
<?php
// 3. Perform database query
$id=$_SESSION['id'];
$author=$_GET['author'];
$quotation=$_GET['quote'];
//below code is to check
echo $id . "<br>". $author . "<br>". $quotation ."<br>";
//4. update query
$query = "UPDATE 'quotations' SET
'author' = '$author',
'quotation' = '$quotation',
WHERE 'id' = '$id'";
mysql_query($query);
// test to see if the update occurred
if (mysql_affected_rows() == 1) {
// Success!
echo "The page was successfully updated.";
} else {
echo "The page could not be updated.";
}
?>
<?php
// 5. Close connection
mysql_close($connection);
session_destroy();
//header("Location: Admin.php"); commented just to observe the output.
?>
</body>
</html>
by echo before query i`m getting my edit values which means there is no issue with the form, even db connected but no updates. Any suggession in this regard will be appreciated.
MySQL-escape your variables! Or better yet: use the mysqli/PDO prepared statements.
Additionally, your tablename is wrapped in single-quotes, and there is a stray comma before your WHERE clause. Use backquotes instead (or no quotes at all should be fine for that table name.)
$query = "UPDATE `quotations` SET
'author' = '$author',
'quotation' = '$quotation'
WHERE 'id' = '$id'";
MySQLi: http://php.net/manual/en/book.mysqli.php
MySQLi Prepared Statements: http://php.net/manual/en/mysqli.prepare.php
PDO: http://php.net/manual/en/book.pdo.php
PDO Prepared Statement method: http://php.net/manual/en/pdo.prepare.php
Is the id attribute in the database a numeric field? If so, you shouldn't be adding the single quotes in the UPDATE string.
$query = "UPDATE 'quotations' SET
'author' = '$author',
'quotation' = '$quotation',
WHERE 'id' = $id"
Related
I would like to have a page that, when someone clicks a pre-formatted link I've sent, writes a variable in the URL to a MySQL database and just displays "Thank You" or something to the user.
Example:
The user would click a link formatted something like http://www.example.com/click.php?id=12345
When the page loads the 12345 would be written to a table in a MySQL database, it would show a Thank you, and that is it.
Seems like it should be simple enough but I can't find anything on it. I'm probably searching wrong, since this is all new to me.
Your best bet is to utilise $_GET['id'] which will take in the value from your url.
After grabbing the id from your url you will want to use PDO or mysqli prepared statements in order to protect yourself from sql injection.
I hope this helps.
Updated as per Kevin Voorn's comment.
if(isset($_GET['id']) && !empty($_GET['id'])) {
$logged_id = $_GET['id'];
$stmt = $mysqli->prepare("INSERT INTO tableName (`logged_id`) VALUES (?)");
$stmt->bind_param('i', $logged_id);
$stmt->execute();
if($stmt->affected_rows > 0){
echo "Thank You.";
}
$stmt->close();
}
User $_GET to retrive the value and put into your table.
Example:
code inside click.php
<?php
$id=$_GET['id'];
$sql="Insert into table1 VALUES ($id)";
mysqli_query($connect,$sql);
echo "<script>alert('Thank you')</script>";
?>
Thanks for the responses. I ended up finding this page: https://www.binpress.com/tutorial/using-php-with-mysql-the-right-way/17 that described the process for using mysqli to connect to my database. I used that page to create the necessary functions in ../db.php and included it in the actual PHP script that would catch the url. My script ended up looking like this:
<?php
require '../db.php';
date_default_timezone_set('UTC');
$date = date("Y-m-d H:i:s T");
$db = new Db();
$db_id = $db -> quote($_GET['id']);
$db_date = $db -> quote($date);
$result = $db -> query("INSERT INTO `table` (`id`,`GUID`,`AccessTime`) VALUES (NULL, " . $db_id . "," . $db_date . ")");
if($result === false) {
exit();
} else {
echo "<html><body><center><br><h1>Thank You!</h1></center></body></html>";
}
?>
Please help i commented off some stuff for testing purposes but nothing works
<?php
//retrieve the data sent in the POST request
$yourDateOrdered =$_POST["DateOrdered"];
$yourDueDate = $_POST["DueDate"];
if(isset($_POST["CompanyName"])){$yourCompanyName = $_POST["CompanyName"];}
//Validate the fields
if ($yourDateOrdered=="" || $yourDateOrdered==null){
$err= $err."Please enter the date the purchase order was made<br>";
}
if ($yourDueDate=="" || $yourDueDate==null){
$err= $err. "Please enter a date when the item is required<br>";
}
//if ($yourCompanyName=="" || $yourCompanyName==null){
//$err= $err."Please enter the customer name<br>";
//}
//Connect to the server and select database
include("dbConnection.php");
//define sql query to execute on the database
$Query1="INSERT INTO orders(CompanyName, DateOrdered, DueDate)
VALUES ('$yourCompanyName','$yourDateOrdered', '$yourDueDate')";
//execute query
//$result = mysql_query($Query1);
//echo("The following order has been added");
//result of the action stored in $Result
$Result = mysql_query($Query1);
if($Result){
echo 'Order entered';
echo Header ("Location:orderformitem.php");
}
//Close the connection
mysql_close($con);
//Check if query executed successfully and forward the user to an appropriate location
//if($queryResult){
//echo "Order save <br>";
//Header ("Location:../PHP/orderformitem.php");
//}
?>
You definietly need to learn how to debug. First, comment out the Header('Location ...'); row, to catch errors.
add error_reporting(E_ALL); and display_errors(1); at top of your file, to see any errors.
Let's var_dump($_POST) to see, is all the variables are correct.
Do a date validation, if you are want correct dates.
Dump your query, and try to run it in sql directly.
DO NOT use mysql functions because they are deprecated. Use mysqli or PDO instead.
Escape your data, to avoid sql injections!
<?php
require ("db/db.php");
$c_id = ($_POST['c_id']);
$c_title = ($_POST['c_title']);
$c_content = ($_POST['c_content']);
// echo place
$sql = mysql_query("UPDATE content
SET c_id = $c_id, c_title = $c_title, c_content = $c_content
WHERE c_id = $c_id");
header("location: index.php");
?>
This is my code.
when the header goes to the index, nothig has changed in the fields that are presented here.
i tried to echo the variables at the "echo place" and they all returned correct,
so i know that they are POSTed to the page.
i guess the error are in the SQL UPDATE statement, but PHP does not return any error to me,
it just goes directly to the index.php.
when i try to run the SQL in phpmyadmin, whith value 1 instead of the variable, it changes all the fields to 1, so there it works.
1) You should use mysql_real_escape_string()
2) why your are updating the id of a table? you also need to change your query
3) use quotes in your php variable
Try like this:
require ("db/db.php");
$c_id = mysql_real_escape_string($_POST['c_id']);
$c_title = mysql_real_escape_string($_POST['c_title']);
$c_content = mysql_real_escape_string($_POST['c_content']);
// echo place
$sql = mysql_query("UPDATE content
SET c_title = '$c_title', c_content = '$c_content'
WHERE c_id = $c_id limit 1") or die(mysql_error());
header("location: index.php");
You should switch to mysqli or PDO since mysql_* are outdated and will be removed.
Just to be sure, try this code (As I don't know the variables content, I put all of those with "'"
$sql = <<<SQL
UPDATE content
SET c_id='{$c_id}', c_title='{$c_title'}, c_content='{$c_content}'
WHERE c_id='{$c_id}'
SQL;
$query = mysql_query($sql);
var_dump($query);
And if the $query returns true, put the header('Location: index.php"); again
I am working on a program that takes HTML code made by a WYSIWYG editor and inserting it into a database, then redirecting the user to the completed page, which reads the code off the database. I can manually enter code in phpmyadmin and it works but in PHP code it will not overwrite the entry in the code column for the ID specified. I have provided the PHP code to help you help me. The PHP is not giving me any parse errors. What is incorrect with the following code?
<?php
//POST VARIABLES------------------------------------------------------------------------
//$rawcode = $_POST[ 'editor1' ];
//$code = mysqli_real_escape_string($rawcode);
$code = 'GOOD';
$id = "1";
echo "$code";
//SQL VARIABLES-------------------------------------------------------------------------
$database = mysqli_connect("localhost" , "root" , "password" , "database");
//INSERT QUERY DATA HERE----------------------------------------------------------------
$queryw = "INSERT INTO users (code) VALUES('$code') WHERE ID = '" . $id . "'";
mysqli_query($queryw, $database);
//REDIRECT TO LOGIN PAGE----------------------------------------------------------------
echo "<script type='text/javascript'>\n";
echo "window.location = 'http://url.com/users/" . $id . "/default.htm';\n";
echo "</script>";
?>
Your problem is that mysql INSERT does not support WHERE. Change the query to:
INSERT INTO users (code) VALUES ('$code')
Then to update a record, use
UPDATE users SET code = '$code' WHERE id = $id
Of course, properly prepare the statements.
Additionally, mysqli_query requires the first parameter to be the connection and second to be the string. You have it reversed. See here:
http://php.net/manual/en/mysqli.query.php
It should also be noted that this kind of procedure should be run before the output to the browser. If so, you can just use PHP's header to relocate instead of this js workaround. However, this method will still work as you want. It is just likely to be considered cleaner if queries and relocation is done at the beginning of the script.
I'm doing a transaction with PHP and MySQL. Using PHPMyAdmin I'm inserting queries into my University DB, where I'm supposed to use transactions in some tables. So far I've made this code for my Staff transactions, but my problem is how can I get the information inserted in addStaff.php so I can use it as a query on this code? right where it says //values();
<?php
function begin()
{
mysql_query("BEGIN");
}
function commit()
{
mysql_query("COMMIT");
}
function rollback()
{
mysql_query("ROLLBACK");
}
mysql_connect("localhost","username", "password") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
$query = "INSERT INTO Staff (id,name,position,phone,email,roomNumber,dnumber)"
//values();
begin(); // BEGIN
$result = mysql_query($query);
if(!$result)
{
rollback(); // ROLLBACK
echo "You rolled back";
exit;
}
else
{
commit(); // COMMIT
echo "Transaction was succesful";
}
?>
This is maybe what you're looking for:
$new_row = mysql_insert_id();
$query = mysql_query("SELECT * FROM `Staff` WHERE `id`=".$new_row);
$r = mysql_fetch_assoc($query);
echo $r['name'];
will echo the inserted rows name.
Edit: This is a very very basic version of how to do things, before moving anything to production you need to read up on SQL Injection, Prepared Statements/Escaping User Input, XSS Attacks and many more vital parts of SQL query security
If I understand you question correct, you need to know how to prompt for data, accept it, and insert it into the database:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
... connect to the database ...
$sometext = $_POST['textfield']; // retrieve the value from the form
$qsometext = mysql_real_escape_string($sometext); // make it safe for the query
$sql = "INSERT INTO mytable (textfield) VALUES ($qsometext);" // build the sql query
$result = mysql_query($sql) or die(mysql_error()); // run the query
}
?>
<html>
<body>
<form method="POST">
<input type="text" name="textfield"><input type="submit">
</form>
</body>
</html>
That's a barebones version of how to show a form, then insert the user's data into a database, the simply re-displays the form for more data.