I've created a text posting website. Except the posting on the post.php page I want to enable users to post text when they type www.mywebsite.com/post.php?name=MyName&body=MyText? How can I make this?
The post code looks like this:
<?php
//insert category to database
if(isset($_POST['qty'])) {
// Fetch and clean the <select> value.
// The (int) makes sure the value is really a integer.
$qty = (int)$_POST['qty'];
// Create the INSERT query.
$sql = "INSERT INTO `table`(`quantity`)
VALUES ({$qty})";
// Connect to a database and execute the query.
$dbLink = mysql_connect('MyServer', 'username', 'password') or die(mysql_error());
mysql_select_db('database_name', $dbLink) or die(mysql_errno());
$result = mysql_query($sql);
// Check the results and print the appropriate message.
if($result) {
echo "Record successfully inserted!";
}
else {
echo "Record not inserted! (". mysql_error() .")";
}
}
if ($_POST['post'])
{
//get data
$title = $_POST['title'];
$body = $_POST['body'];
//check for existance
if ($title&&$body)
{
mysql_connect("MyServer","username","password") or die(mysql_error());
mysql_select_db("database_name") or die(mysql_error());
$date = date("Y-m-d");
//insert data
$insert = mysql_query("INSERT INTO news VALUES ('','$title','$body','$date')") or die(mysql_error());
die("Your text has been posted!");
}
else
echo "Please fill out your name and text";
}
?>
You will want to use $_GET not POST for the data from the query string.
//get data
$title = $_GET['title']; // or name if it's name
$body = $_GET['body'];
Try to use $_REQUEST - it has all the data you have posted to the script (from $_GET, $_POST and $_COOKIE global arrays)
First suggestion is, avoid direct queries based on query strings at all possible costs! This is a huge security concern.
Also, the code you supplied would is open to numerous security holes and concerns.
Anytime you call a variable via $_COOKIE, $_POST or $_GET and it is used in a query, use MySQLI/PDO Prepared statements when possible, or at least mysql_real_escape_string. This will attempt to sanitize the data going into your database.
Also, You are GETTING parameters from the the url/query string, change POST to GET.
Additionally, your line which says:
if($_GET['post'])
Will always fail, you do not have a parameter in your url called post. For that to work, it would need to look like:
post.php?post&name=MyName&body=MyText?)
See below:
<?php
//insert category to database
// makes sure qty is numeric # added by sixeightzero
if(isset($_GET['qty']) && is_numeric($_GET['qty'])) {
// Fetch and clean the <select> value.
// The (int) makes sure the value is really a integer.
$qty = (int)$_GET['qty'];
// Create the INSERT query.
$sql = "INSERT INTO `table`(`quantity`)
VALUES ({$qty})";
// Connect to a database and execute the query.
$dbLink = mysql_connect('MyServer', 'username', 'password') or die(mysql_error());
mysql_select_db('database_name', $dbLink) or die(mysql_errno());
$result = mysql_query(mysql_real_escape_string($sql));
// sanitizes input # added by sixeightzero
// Check the results and print the appropriate message.
if($result) {
echo "Record successfully inserted!";
}
else {
echo "Record not inserted! (". mysql_error() .")";
}
}
if (!isset($_GET['name']) && !isset($_GET['body'])){
//get data
$title = $_GET['name'];
$body = $_GET['body'];
//check for existance
if ($title && $body)
{
mysql_connect("MyServer","username","password") or die(mysql_error());
mysql_select_db("database_name") or die(mysql_error());
$date = date("Y-m-d");
//insert data
$insert = mysql_query("INSERT INTO news VALUES ('','".mysql_real_escape_string($title)."','".mysql_real_escape_string($body)."','".mysql_real_escape_string($date)."')") or die(mysql_error());
// sanitizes input # added by sixeightzero
die("Your text has been posted!");
}
else
echo "Please fill out your name and text";
}
?>
Here's the complete source code!!
Try using this
<?php
//insert category to database
if(isset($_POST['qty'])) {
// Fetch and clean the <select> value.
// The (int) makes sure the value is really a integer.
$qty = (int)$_POST['qty'];
// Create the INSERT query.
$sql = "INSERT INTO `table`(`quantity`)
VALUES ({$qty})";
// Connect to a database and execute the query.
$dbLink = mysql_connect('MyServer', 'username', 'password') or die(mysql_error());
mysql_select_db('database_name', $dbLink) or die(mysql_errno());
$result = mysql_query($sql);
// Check the results and print the appropriate message.
if($result) {
echo "Record successfully inserted!";
}
else {
echo "Record not inserted! (". mysql_error() .")";
}
}
if ($_SERVER['REQUEST_METHOD'] == "GET") //check whether its a GET method
{
//get data, since you know that a valid "GET" request was sent
$title = $_REQUEST['title'];
$body = $_REQUEST['body'];
if (isset($title) && isset($body)) //check for existance
{
mysql_connect("MyServer","username","password") or die(mysql_error());
mysql_select_db("database_name") or die(mysql_error());
$date = date("Y-m-d");
//insert data
$insert = mysql_query("INSERT INTO news VALUES ('','$title','$body','$date')") or die(mysql_error());
die("Your text has been posted!");
}
else
echo "Please fill out your name and text";
}
?>
$_REQUEST is basically the result of array_merge($_GET,$_POST,$_COOKIE), so you can use it to get a value which may be a GET or POST variable.
Related
Hi I am trying to create a little email subscriber script for adding email addresses to my database. I was able to get it working fine using deprecated functions like mysql_connect but am making it better using mysqli instead. However for some reason I am no longer able to insert the email addresses into the database yet I can connect to the database fine and check the email address doesn't already exist. I would like to know why my INSERT doesn't seem to be working. I don't have much experience with PHP thanks.
if (!$link) {
echo "save_failed cannot connect"; //if cant connect show error
return;
}
mysqli_select_db($link,$mydb);
// Clean variables before performing insert
$clean_email = mysqli_real_escape_string($link,$_POST['email']);
$clean_subscriber = mysqli_real_escape_string($link,$_POST['firstname']);
$clean_date = mysqli_real_escape_string($link,$_POST['date']);
$query = "SELECT * FROM EmailList WHERE email = '{$email}'";//check if already in list
$result = mysqli_query($link,$query);
$row_cnt = mysqli_num_rows($result);
if($row_cnt == 0) {
// Perform insert if not in list
$sql = "INSERT INTO EmailList (Email,Name,Date) VALUES
('$clean_email','$clean_subscriber','$clean_date')";
echo "Thank you for Subscribing to my blog!";
} else {
echo "You have subscribed already. Thank you for subscribing";
}
Looks like you're missing the line that runs the query:
mysqli_query($link,$sql);
You need to execute the query with
mysqli_query()
like so:
if (!$link) {
echo "save_failed cannot connect"; //if cant connect show error
return;
}
mysqli_select_db($link,$mydb);
// Clean variables before performing insert
$clean_email = mysqli_real_escape_string($link,$_POST['email']);
$clean_subscriber = mysqli_real_escape_string($link,$_POST['firstname']);
$clean_date = mysqli_real_escape_string($link,$_POST['date']);
$query = "SELECT * FROM EmailList WHERE email = '{$email}'";//check if already in list
$result = mysqli_query($link,$query);
$row_cnt = mysqli_num_rows($result);
if($row_cnt == 0) {
// Perform insert if not in list
$sql = "INSERT INTO EmailList (Email,Name,Date) VALUES
('$clean_email','$clean_subscriber','$clean_date')";
mysqli_query($link,$sql)
echo "Thank you for Subscribing to my blog!";
} else {
echo "You have subscribed already. Thank you for subscribing";
}
I am getting the id from another page but i am not being able to pass it to the sql query. If i define any value to $id instead of 0 then the query works but otherwise it fails.
Secondly, i would like to display the values of the array in respective input fields. I tried using
<?php
echo $result_array['institutename'][0];
?>
in the body part but it didnt work out.
My rest code is as follows:
(I know the mysql functions are deprecated but i would move on to mysqli as soon as i have solved this problem)
<?php
include 'connect.php';
$id=0;
$result_array=array();
if(isset($_REQUEST['id'])){
$id=(int)$_REQUEST['id'];
//$uid=$id;
if(!empty($id)){
$sql = "SELECT * FROM institute WHERE id =$id";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)){
$result_array[]=$row;
}
}
}
if ($_SERVER['REQUEST_METHOD'] == 'POST' && $_POST['form_institutedetails'] == 'saveinstitutedetails')
{
$mysql_table='institute';
$institutename = $_POST['institutename'];
$established = $_POST['established'];
$regno = $_POST['reg_no'];
$branch = $_POST['branch'];
$initials = $_POST['initials'];
$address=$_POST['address'];
$pin=$_POST['pin'];
$contact1=$_POST['contact1'];
$contact2=$_POST['contact2'];
$contact3=$_POST['contact3'];
$fax1=$_POST['fax1'];
$fax2=$_POST['fax2'];
$email=$_POST['email'];
$website=$_POST['website'];
if(isset($_POST['head_office'])){
$head_office=$_POST['head_office'];
}
else{
$head_office="Branch";
}
if (!preg_match("/^.+#.+\..+$/", $email))
{
$error_message = 'Email is not a valid email address. Please check and try again.';
}
if (empty($error_message))
{
$newinstitutename = mysql_real_escape_string($institutename);
$newestablished = mysql_real_escape_string($established);
$newregno = mysql_real_escape_string($regno);
$newbranch = mysql_real_escape_string($branch);
$newaddress = mysql_real_escape_string($address);
$newpin = mysql_real_escape_string($pin);
$newemail = mysql_real_escape_string($email);
$newwebsite = mysql_real_escape_string($website);
$ho = mysql_real_escape_string($head_office);
include 'connect.php';
$sql = "UPDATE `".$mysql_table."` SET `institutename`='$newinstitutename', `established`='$newestablished', `regno`='$newregno', `branch`='$newbranch', `initials`='$initials', `address`='$newaddress', `pin`='$newpin', `contact1`='$contact1', `contact2`='$contact2', `contact3`='$contact3', `fax1`='$fax1', `fax2`='$fax2', `email`='$newemail', `website`='$newwebsite', `head_office`='$ho' WHERE `id`=$id";
$result = mysql_query($sql, $db);
mysql_close($db);
$error_message='Updated Successfully!.';
}
}
?>
When you are unsure about the structure of an array, you can always do a print_r during development.
print_r($result_array);
In this case, it is an index array of associative arrays.
To access the first record's institutename (and probably the only record since it looks like you used an unique key in your query), you can use
echo $result_array[0]['institutename'];
i have code for save 3 textbox in one field in databse
no problem when i am enter 3 textbox , but when i fill 1 textbox and press ok
save another textbox in database as blank
i want just take the textbox is fulled and ignore the textbox empty
this is my code
<?php
include("connect.php");
$expert_name = trim($_POST['expert_name']);
$expert_name2 = trim($_POST['expert_name2']);
$expert_name3 = trim($_POST['expert_name3']);
// this is for arabic language.
mysql_query("SET NAMES utf8");
// Insert data into mysql
$sql="INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name')";
$sql2="INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name2')";
$sql3="INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name3')";
$result=mysql_query($sql);
$result2=mysql_query($sql2);
$result3=mysql_query($sql3);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful";
echo "<BR>";
// echo "<a href='formadd.php'>Back to main page</a>";
}
else {
echo "ERROR";
echo "<br>";
// this for print error in insert process
echo mysql_error();
echo "<a href='expert_add.php'><br>Please try again </a>";
}
//mysql_close($con);
?>
back to form add
Execute your sql query only the variable value not equal to empty.
try this,
$expert_name = trim($_POST['expert_name']);
$expert_name2 = trim($_POST['expert_name2']);
$expert_name3 = trim($_POST['expert_name3']);
// this is for arabic language.
mysql_query("SET NAMES utf8");
// Insert data into mysql
if ($expert_name != "") {
$sql = "INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name')";
$result = mysql_query($sql);
}
if ($expert_name2 != "") {
$sql2 = "INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name2')";
$result2 = mysql_query($sql2);
}
if ($expert_name != "") {
$sql3 = "INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name3')";
$result3 = mysql_query($sql3);
}
// if successfully insert data into database, displays message "Successful".
if ($result || $result2 || $result3) {
echo "Successful";
echo "<BR>";
// echo "<a href='formadd.php'>Back to main page</a>";
} else {
echo "ERROR";
echo "<br>";
// this for print error in insert process
echo mysql_error();
echo "<a href='expert_add.php'><br>Please try again </a>";
}
//mysql_close($con);
?>
back to form add
You should also check $result2 and $result3. I added that in this answer
try this
if ( !empty($_POST['expert_name']) ){
$sql="INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name')";
$result=mysql_query($sql);
}
if ( !empty($_POST['expert_name2']) ){
$sql2="INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name2')";
$result2=mysql_query($sql2);
}
if ( !empty($_POST['expert_name3']) ){
$sql3 ="INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name3')";
$result3 =mysql_query($sql3 );
}
Then you might want to check if the variable is empty().
<?php
include("connect.php");
$expert_name = trim($_POST['expert_name']);
$expert_name2 = trim($_POST['expert_name2']);
$expert_name3 = trim($_POST['expert_name3']);
// this is for arabic language.
mysql_query("SET NAMES utf8");
// Insert data into mysql
if(!empty($expert_name)) {
$sql="INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name')";
$result=mysql_query($sql);
}
if(!empty($expert_name2)) {
$sql2="INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name2')";
$result2=mysql_query($sql2);
}
if(!empty($expert_name3)) {
$sql3="INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name3')";
$result3=mysql_query($sql3);
}
// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful";
echo "<BR>";
// echo "<a href='formadd.php'>Back to main page</a>";
}
else {
echo "ERROR";
echo "<br>";
// this for print error in insert process
echo mysql_error();
echo "<a href='expert_add.php'><br>Please try again </a>";
}
Also note: You only check if $result is okay. If you only fill textbox 2 and leave 1 empty, the value of 2 it will get inserted but an error is shown.
I'd say your code need general review, but as it is for now you will have to do something like this each query:
if (!empty($expert_name2){
$result2=mysql_query($sql2)
}
But you should try to loop your queries in foreach rather than manually write every on query. And by the way:
if($result){
echo "Successful";
echo "<BR>";
// echo "<a href='formadd.php'>Back to main page</a>";
}
This code only return succes when 1st wuery success because you use $result which is set in 1st query only
The ID is probably NOT NULL AUTO_INCREMENT, so that won't accept NULL as value.
try sending blank value, such as:
$sql="INSERT INTO experts(id,expert_name) VALUES ('', '$expert_name')";
Also, build bulk insert, rather than multiple.
I will explain why, when you insert single insert into the database, the values being inserted, then, the DB engine flushes indexes (they written to disk), unless you have set delay_key_write=ALL in you my.cnf. Index flushing directly affects your db performance.
Please, check the reworked code out. The code adjusted for bulk insert, sql string escaping for security purposes and additional verification for post keys existence.
<?php
include("connect.php");
// this is for arabic language.
mysql_query("SET NAMES utf8");
$values = array();
$skipInsert = true;
$fields = array('expert_name', 'expert_name2', 'expert_name3');
$insert = "INSERT INTO experts(id,expert_name) VALUES ";
// Loop through predefined fields, and prepare values.
foreach($fields AS $field) {
if(isset($_POST[$field]) && !empty($_POST[$field])) {
$values[] = "('', '".mysql_real_escape_string(trim($_POST[$field]))."')";
}
}
if(0 < sizeof($values)) {
$skipInsert = false;
$values = implode(',', $values);
$insert .= $values;
}
if(false === $skipInsert) {
mysql_query($insert);
}
// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful","<BR>";
// echo "<a href='formadd.php'>Back to main page</a>";
} else {
echo "ERROR","<br>",mysql_error(),"<a href='expert_add.php'><br>Please try again </a>";
}
HTH,
VR
if(!empty($textbox1_value)) {
//DO SQL
}
You can repeat this for multiple boxes however you wish, the empty operator checks if its empty, so if its not empty the "//DO SQL" area will get run.
Can anyone tell me why I am getting an Undefined Index error on my code here.
I have used this setup using the if(isset) condition in other parts of my project after
researching my original Undefined Index errors and ISSET fixed my problems. But it is not working here for some reason and I cannot see why.
This form is POSTING the input:
<form action="addAlbum_Processed.php" method="POST">
<p>Enter artistID of Artist<input type="number" name="artist_id" maxlength="2" size="2"></p>
<p>Enter name of Album to be created<input type="text" name="album_name" size="20"></p>
<input type="submit" name="submit" value="submit"></form>
and this page is processing the form input and updating the albums table in my database:
<?php
$connection = mysql_connect('localhost','root','')
or die(mysql_error());
echo "Connected to php Server <br>";
or die("Could not select assi2 database");
echo "Connected to assi2 database <br>";
if(isset($_POST['submit']))
{
$album_name = $_POST['album_name'];
$artist_id = $_POST['artist_id'];
}
$album_name = $_POST['album_name'];
$artist_id = $_POST['artist_id'];
$sqlQuery = "SELECT * FROM albums WHERE album = '{$album_name}'";
$result = mysql_query($sqlQuery, $connection) or die("Selection Query Failed !!!");
if (mysql_num_rows($result) != 0)
{
header ("Location: Album_Exists.html");
}
else
{
$sqlInsert = "INSERT INTO albums (ArtistID, Album, delete_marker)
VALUES ('{$artist_id}','{$album_name}','delete_marker = 0')";
$result = mysql_query($sqlInsert, $connection) or die("Selection Query Failed !!!");
header ("Location: addAlbum_Processed.php");
}
mysql_close($connection);
?>
I cannot see where I am going wrong. Regards, TW
This is a tiny example of your problem:
if(isset($_POST['submit']))
{
$album_name = $_POST['album_name'];
$artist_id = $_POST['artist_id'];
}
You check whether a submit form field was posted before using the other fields. So far, so good. (I would check for the fields that were going to be used, but at least you're checking something.)
But then:
$album_name = $_POST['album_name'];
$artist_id = $_POST['artist_id'];
You use the fields anyway.
What's more...you don't keep from trying to insert stuff if a form isn't being posted. So any time some rogue spider visits your page, you end up with a blank album in your database.
And that's not even mentioning the fact that you're still using mysql_query.
if(isset($_POST['submit']))
{
$album_name = $_POST['album_name'];
$artist_id = $_POST['artist_id'];
}
|__________________________| first
$album_name = $_POST['album_name'];
$artist_id = $_POST['artist_id'];
|_________________________| Repeated
you are fetching variables twice.only one that is if condition is enough.Also use isset for both the variables.
if(isset($_POST['submit']))
{
if isset($_POST['album_name'])
$album_name = $_POST['album_name'];
if isset($_POST['artist_id'])
$artist_id = $_POST['artist_id'];
}
Try something like in addalbam_process.php
<?php
$connection = mysql_connect('localhost','root','')
or die(mysql_error());
echo "Connected to php Server <br>";
or die("Could not select assi2 database");
echo "Connected to assi2 database <br>";
if(isset($_POST['submit']))
{
if(isset($_POST['albam_name']){$album_name = $_POST['album_name']};
if(isset($_POST['artist_id']){$artist_id = $_POST['artist_id']};
}
$sqlQuery = "SELECT * FROM albums WHERE album = '{$album_name}'";
$result = mysql_query($sqlQuery, $connection) or die("Selection Query Failed !!!");
if (mysql_num_rows($result) != 0)
{
header ("Location: Album_Exists.html");
}
else
{
$sqlInsert = "INSERT INTO albums (ArtistID, Album, delete_marker)
VALUES ('{$artist_id}','{$album_name}','delete_marker = 0')";
$result = mysql_query($sqlInsert, $connection) or die("Selection Query Failed !!!");
header ("Location: addAlbum_Processed.php");
}
mysql_close($connection);
Please, use MYSQLI or PDO to Prevent SQL INJECTION
here </form> is missing
and try something like this
if(isset($_POST['submit']))
{
$album_name = $_POST['album_name'];
$artist_id = $_POST['artist_id'];
}
A few things.
This line 'delete_marker = 0' should most probably read as
VALUES ('{$artist_id}','{$album_name}','0')
or VALUES ('{$artist_id}','{$album_name}',0)
As I read it 'delete_marker = 0' you are attempting to actually write this value inside the delete_marker column (ArtistID, Album, delete_marker)
Or, you're attempting to use a WHERE delete_marker = 0 clause, which can't be used in an INSERT INTO, but an UPDATE or SELECT rather.
And your if(isset($_POST['submit'])) conditional statement should be wrapping your entire code, instead of just your 2 form variables, because it's basically saying "Ok, assign these 2 variables, then ignore the rest if it's NOT set."
Plus, you're repeating those 2 input variables.
$album_name = $_POST['album_name'];
$artist_id = $_POST['artist_id'];
(I wrapped your entire code inside the if(isset($_POST['submit'])) conditional statement, btw.
Side note: If you're having a DB connection issue, use this instead:
$connection = mysql_connect('localhost', 'root', '');
if (!$connection) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
PHP Give this a try:
Sidenote: If this line fails VALUES ('{$artist_id}','{$album_name}', 0) put quotes around the 0 as in '0'
<?php
$connection = mysql_connect('localhost','root','')
or die(mysql_error());
echo "Connected to php Server <br>";
or die("Could not select assi2 database");
echo "Connected to assi2 database <br>";
if(isset($_POST['submit']))
{
$album_name = $_POST['album_name'];
$artist_id = $_POST['artist_id'];
$sqlQuery = "SELECT * FROM albums WHERE album = '{$album_name}'";
$result = mysql_query($sqlQuery, $connection) or die("Selection Query Failed !!!");
if (mysql_num_rows($result) != 0)
{
header ("Location: Album_Exists.html");
}
else
{
$sqlInsert = "INSERT INTO albums (ArtistID, Album, delete_marker)
VALUES ('{$artist_id}','{$album_name}', 0)"; // or add quotes around the zero
$result = mysql_query($sqlInsert, $connection) or die("Selection Query Failed !!!");
header ("Location: addAlbum_Processed.php");
}
} // closing brace for if(isset($_POST['submit']))
mysql_close($connection);
?>
I have this class am using to perform queries - insert, delete, drop create etc, but this time i created a method to update a table when the update have been submitted and to my surprise and hours of headache it is return success but not actually updating the record in the database am so confused, I have been debugging for hours to no avail
so i decided to share my worries to see if i can receive help as am actually 2 weeks old In OOP PHP
so here my class
class queryClass extends MYSQL{ //MYSQL is for connecting to database
//table fields
var $user_table = ''; //table names that will be used in all names, each query method will input its own table name
//connect to database
function dbconnect(){
MYSQL::dbconnect();
}
//prevent injection
function qry($query) {
$this->dbconnect();
$args = func_get_args();
$query = array_shift($args);
$query = str_replace("?", "%s", $query);
$args = array_map('mysql_real_escape_string', $args);
array_unshift($args,$query);
$query = call_user_func_array('sprintf',$args);
$result = mysql_query($query) or die(mysql_error());
if($result){
return $result;
}else{
$error = "Error";
return $result;
}
//update quote function
function updatequote($table, $message1, $message2, $column_name1, $column_name2, $column_name3, $quote_id){
$this->dbconnect();
$this->quote_id = $quote_id;
echo $message1, $message2;
//make sure table name is set
$this->user_table = $table;
$this->column_name1 = $column_name1;
$this->column_name2 = $column_name2;
$this->column_name3 = $column_name3;
//execute login via qry function that prevents MySQL injections
$result = $this->qry("UPDATE ".$this->user_table." SET ".$this->column_name2."='?', ".$this->column_name3."='?'
WHERE ".$this->column_name1."='?';", $message1, $message2, $this->quote_id );
// $result = mysql_query("INSERT INTO ".$this->user_table."(username, password) VALUES('$username', '$password')");
if($result){
$_SESSION['success'] = "The Update Was Successfully Saved";
header('location: edit_quotes.html');
exit();
return true;
}else{
$_SESSION['success'] = "The Update Was Not Saved".mysql_error();
header('location: edit_quotes.html');
exit(); //do something on FAILED login
return false;
}
}
//quote form
function quoteEditorform($formname, $formclass, $formaction, $helptext, $first, $second){
//conect to DB
$this->dbconnect();
echo"
<form name=\"$formname\" method=\"post\" id=\"$formname\" class=\"$formclass\" enctype=\"application/x-www-form-urlencoded\" action=\"$formaction\">
<h2>$helptext</h2>
<div><label for=qoute>NGWA QUOTE
<input type=button value='Quote' onclick=\"wrapInTags(this.form.message1,'quote')\">insert [quote].[/quote]tags
</label>
<textarea name=\"message1\" cols=\"40\" rows=\"4\" onclick=\"copySelection(this)\">$first</textarea><br>
</div>
<div><label for=\"qoute\">ENGLISH MEANING
<input type=button value='Meaning' onclick=\"wrapInTags(this.form.message2,'meaning')\">
insert [meaning].[/meaning]tags
</label>
".$record['meaning']."
<textarea name=\"message2\" cols=\"40\" rows=\"4\" onclick=\"copySelection(this)\">$second</textarea></div>
<input name=\"action\" id=\"action\" value=\"sendeditedquote\" type=\"hidden\">
<div>
<input name=\"submit\" id=\"submitV value=\"Save\" type=\"submit\"></div>
</form>
<div align=\"center\">Read Before Posting</div>
"; }
function createquotetable($tablename){
//connect to DB
$this->dbconnect();
$qry = "CREATE TABLE IF NOT EXISTS ".$tablename."(
quote_id INT(8) NOT NULL AUTO_INCREMENT,
ngwaquote TEXT NOT NULL,
meaning TEXT NOT NULL,
saved_date date,
PRIMARY KEY (quote_id)
) TYPE=INNODB
";
$result = $this->qry($qry);
return;
}
here's my quote-editor.html after including my class files
// instantiate all other needed classes
$cleaner = new cleanPost();
$connect = new MySQL();
$connect->dbconnect();// connect to a database
$bbcode = new BBCode();
$log = new logmein();
if($_REQUEST['action'] == "sendeditedquote"){
//post all the values to the database using our main class
/*topic field checking */
if($_REQUEST['message1'] == "" || $_REQUEST['topic'] > 600) {
$errmsg_arr[] = 'Sorry You Can\'t Send An Empty Qoute OR quote greater than 500 characters at a time';
$errflag = true;
}
if($_REQUEST['message2'] == "" ) {
$errmsg_arr[] = 'Sorry You Can\'t Update With An Empty Qoute';
$errflag = true;
}
//If there are input validations, redirect back
if($errflag) {
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
session_write_close();
header("location: edit_quotes.html");
exit();
}
$log->updatequote("quotes", $_REQUEST['message1'], $_REQUEST['message2'], "quote_id", "ngwaquote", "meaning", $cleaner->clean($_GET['quote_id']));
}
ai'ght when i perform the query the success/error line returns that the update was successful but on the other page where i display all available quotes the particular quote still is NOT updated
Anyone who's experienced such please tell me what am gon' do.
BEING ASKED THE LINE FOR THE RAW QUERY
HERE IS IT-
first is the the method that cleanse ouy my post and the I use it for query using $this->qry(somequeries here)
function qry($query) {
$this->dbconnect();
$args = func_get_args();
$query = array_shift($args);
$query = str_replace("?", "%s", $query);
$args = array_map('mysql_real_escape_string', $args);
array_unshift($args,$query);
$query = call_user_func_array('sprintf',$args);
$result = mysql_query($query) or die(mysql_error());
if($result){
return $result;
}else{
$error = "Error";
return $result;
}
//update quote function using $this->qry()
function updatequote($table, $message1, $message2, $column_name1, $column_name2, $column_name3, $quote_id){
$this->dbconnect();
$this->quote_id = $quote_id;
echo $message1, $message2;
//make sure table name is set
$this->user_table = $table;
$this->column_name1 = $column_name1;
$this->column_name2 = $column_name2;
$this->column_name3 = $column_name3;
//execute login via ****qry function**** that prevents MySQL injections
$result = $this->qry("UPDATE ".$this->user_table." SET ".$this->column_name2."='?', ".$this->column_name3."='?'
WHERE ".$this->column_name1."='?';", $message1, $message2, $this->quote_id );
// $result = mysql_query("INSERT INTO ".$this->user_table."(username, password) VALUES('$username', '$password')");
if($result){
$_SESSION['success'] = "The Update Was Successfully Saved";
header('location: edit_quotes.html');
exit();
return true;
}else{
$_SESSION['success'] = "The Update Was Not Saved".mysql_error();
header('location: edit_quotes.html');
exit(); //do something on FAILED login
return false;
}
}
If the where clause of your update statement does not match any rows, the update statement will return success.
However it will not change anything.
Note that MySQL knows when a value has not really changed so the statement
UPDATE table1 SET col1 = 0 WHERE col1 = 0
Will always return 0 for the number of affected rows.
If you want to know if anything has been changed you need to call:
$rows_updated = mysql_affected_rows($this->connection);
or
$rows_updated = mysqli_affected_rows($this->connection); //if you're using mysqli
An update statement will only indicate failure is an error has occured.
A warning about SQL-injection
I notice that you use dynamic table and column names.
If those values are in any way alterable by a user or pass through superglobals that can be affected by another php session that can be affected by a user, you have an SQL-injection hole.
Here's how to secure yourself against that: How to prevent SQL injection with dynamic tablenames?
I think i have found the answer to my problem
In the place i had the $this->quote_id i later figured out that the page editor url was editor.html?quote_id=1
then when I submitted it will now process the form on a flat url === editor.html so my mistake was that I didn't request for the QUOTE ID when i was still on the editing url editor.html?quote_id=1 instead requesting for it when it was not possible ie in editor.html so it was meant to return empty quote id which i used to update thereby resulting in update success but not really updating anything
so
all I did was add an input tag hidden to get the quote_id being edited and then post it along with the rest of the form
So simple but took me me hours of rereading and re coding, wonderful,
small things cause much frustration
Thanks all
if the fields you are updating is not the same has the fields in the database, it will not update. although it return success simple means that it sees the table and connect to the database