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.
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>";
}
?>
I am trying to select rows in my table sql. I have done this many times and for this instant it wouldn't work.
Displaying the variable $id, displays correct value, which means it receives a correct value from $_POST however after using it on Select Statement and using mysql_fetch_array, nothing displays.
my code
$id=$_POST['idsend'];
$edit = mysql_query("SELECT * FROM students WHERE id= '$id'") or die(mysql_error());
$fetch=mysql_fetch_array($edit);
echo 'ID= '.$id; ---------> This one displays properly
echo 'ID= '.$fetch['id']; --------> displays nothing
Please help me find out what's wrong. Hehe thanks in advance.
It would be safer to use PDO, to prevent SQL Injection (I made a PDO example of your query):
// it's better to put the following lines into a configuration file!
$host = "enter hostname here";
$dbname = "enter dbname here";
$username = "enter db username here";
$password = "enter db password here";
// setup a PDO connection (needs some error handling)
$db_handle = new PDO("mysql:host=$host;dbname=$dbname;", $username, $password);
// prepare and execute query
$q_handle = $db_handle->prepare("select * from students where id = ?");
$id = $_POST["idsend"];
$q_handle->bindParam(1, $id);
$q_handle->execute();
// get stuff from array
$arr = $q_handle->fetch(PDO::FETCH_ASSOC);
echo $arr["id"];
First of all, you shouldn't use mysql_* functions anymore.
You code fails because mysql_fetch_array() only returns a resource, you need to loop over it to get the actual result.
while ( $row = mysql_fetch_array( $edit ) ) {
printf( 'ID: %s', $row['id'] );
}
Okay, I have found out what's wrong. I apologize for disturbing everyone. I have realized what's wrong in my code and you won't find it on the code I posted in my question.
Carelessness again is the cause for all these. :) hehe
This is where the error is coming from
<form action="" method="post">
<input type="hidden" name="idsend" value="' . $row['id'] . '"/>
I have assigned a variable on a value with extra spaces/character? So the code must look like this.
<input type="hidden" name="idsend" value="'.$row['id'].'"/>
It must be assigned properly to work smoothly with the select statement.
I guess echo-ing the values isn't enough to see if there's something wrong.
Sorry for the trouble.
There are not really and direct answers on this, so I thought i'd give it a go.
$myid = $_POST['id'];
//Select the post from the database according to the id.
$query = mysql_query("SELECT * FROM repairs WHERE id = " .$myid . " AND name = '' AND email = '' AND address1 = '' AND postcode = '';") or die(header('Location: 404.php'));
The above code is supposed to set the variable $myid as the posted content of id, the variable is then used in an SQL WHERE clause to fetch data from a database according to the submitted id. Forgetting the potential SQL injects (I will fix them later) why exactly does this not work?
Okay here is the full code from my test of it:
<?php
//This includes the variables, adjusted within the 'config.php file' and the functions from the 'functions.php' - the config variables are adjusted prior to anything else.
require('configs/config.php');
require('configs/functions.php');
//Check to see if the form has been submited, if it has we continue with the script.
if(isset($_POST['confirmation']) and $_POST['confirmation']=='true')
{
//Slashes are removed, depending on configuration.
if(get_magic_quotes_gpc())
{
$_POST['model'] = stripslashes($_POST['model']);
$_POST['problem'] = stripslashes($_POST['problem']);
$_POST['info'] = stripslashes($_POST['info']);
}
//Create the future ID of the post - obviously this will create and give the id of the post, it is generated in numerical order.
$maxid = mysql_fetch_array(mysql_query('select max(id) as id from repairs'));
$id = intval($maxid['id'])+1;
//Here the variables are protected using PHP and the input fields are also limited, where applicable.
$model = mysql_escape_string(substr($_POST['model'],0,9));
$problem = mysql_escape_string(substr($_POST['problem'],0,255));
$info = mysql_escape_string(substr($_POST['info'],0,6000));
//The post information is submitted into the database, the admin is then forwarded to the page for the new post. Else a warning is displayed and the admin is forwarded back to the new post page.
if(mysql_query("insert into repairs (id, model, problem, info) values ('$_POST[id]', '$_POST[model]', '$_POST[version]', '$_POST[info]')"))
{
?>
<?php
$myid = $_POST['id'];
//Select the post from the database according to the id.
$query = mysql_query("SELECT * FROM repairs WHERE id=" .$myid . " AND name = '' AND email = '' AND address1 = '' AND postcode = '';") or die(header('Location: 404.php'));
//This re-directs to an error page the user preventing them from viewing the page if there are no rows with data equal to the query.
if( mysql_num_rows($query) < 1 )
{
header('Location: 404.php');
exit;
}
//Assign variable names to each column in the database.
while($row = mysql_fetch_array($query))
{
$model = $row['model'];
$problem = $row['problem'];
}
//Select the post from the database according to the id.
$query2 = mysql_query('SELECT * FROM devices WHERE version = "'.$model.'" AND issue = "'.$problem.'";') or die(header('Location: 404.php'));
//This re-directs to an error page the user preventing them from viewing the page if there are no rows with data equal to the query.
if( mysql_num_rows($query2) < 1 )
{
header('Location: 404.php');
exit;
}
//Assign variable names to each column in the database.
while($row2 = mysql_fetch_array($query2))
{
$price = $row2['price'];
$device = $row2['device'];
$image = $row2['image'];
}
?>
<?php echo $id; ?>
<?php echo $model; ?>
<?php echo $problem; ?>
<?php echo $price; ?>
<?php echo $device; ?>
<?php echo $image; ?>
<?
}
else
{
echo '<meta http-equiv="refresh" content="2; URL=iphone.php"><div id="confirms" style="text-align:center;">Oops! An error occurred while submitting the post! Try again…</div></br>';
}
}
?>
What data type is id in your table? You maybe need to surround it in single quotes.
$query = msql_query("SELECT * FROM repairs WHERE id = '$myid' AND...")
Edit: Also you do not need to use concatenation with a double-quoted string.
Check the value of $myid and the entire dynamically created SQL string to make sure it contains what you think it contains.
It's likely that your problem arises from the use of empty-string comparisons for columns that probably contain NULL values. Try name IS NULL and so on for all the empty strings.
The only reason $myid would be empty, is if it's not being sent by the browser. Make sure your form action is set to POST. You can verify there are values in $_POST with the following:
print_r($_POST);
And, echo out your query to make sure it's what you expect it to be. Try running it manually via PHPMyAdmin or MySQL Workbench.
Using $something = mysql_real_escape_string($POST['something']);
Does not only prevent SQL-injection, it also prevents syntax errors due to people entering data like:
name = O'Reilly <<-- query will bomb with an error
memo = Chairman said: "welcome"
etc.
So in order to have a valid and working application it really is indispensible.
The argument of "I'll fix it later" has a few logical flaws:
It is slower to fix stuff later, you will spend more time overall because you need to revisit old code.
You will get unneeded bug reports in testing due to the functional errors mentioned above.
I'll do it later thingies tend to never happen.
Security is not optional, it is essential.
What happens if you get fulled off the project and someone else has to take over, (s)he will not know about your outstanding issues.
If you do something, finish it, don't leave al sorts of issues outstanding.
If I were your boss and did a code review on that code, you would be fired on the spot.
Having trouble getting my form to UPDATE records in my database even after searching the web and viewing the other answers on stack-overflow.
Here is my current NON functioning code:
if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "form1")) {
session_start();
$tablename = $_SESSION['MM_Username'];
$amount=$_POST['amount'];
$UpdateQuery = "UPDATE '" . $tablename . "' SET stock = '" . $amount . "' WHERE status = 1";
mysql_query($UpdateQuery);
}
The table i want to update has the same name as the SESSION variable MM_Username. I have a form with a textbox named amount and a Submit button that when clicked, should trigger the above code. If you need to know anything else let me know. Thanks in advance!
You're using the wrong quotes around your table name. Also, your query is open to SQL injection. Consider using PDO and bind parameters.
$UpdateQuery = sprintf('UPDATE `%s` SET `stock` = :amount WHERE `status` = 1',
$tablename);
$stmt = $pdo->prepare($UpdateQuery);
$stmt->bindParam('amount', $amount);
$stmt->execute();
Have MySQL tell you what the problem is. Change the last line of your code to this:
if (!mysql_query($UpdateQuery)) {
echo mysql_error();
}
Print out if you are having your tablename in your session variable.
print $_SESSION['MM_Username'];
Also print out the $UpdateQuery and see how the mysql query is formed. Copy that query & try running it manually in mysql to see if the query is ok.
ADVISE: I see that you have used $_POST. This is fine, but I advise you to use $_REQUEST. This var in PHP has all $_POST & $_GET content. Sometimes one forgets to change the $_POST to $_GET or vice versa & ends up wasting his time, debuggin.
if (!mysql_query($UpdateQuery)) {
echo mysql_error()
}
This is my code to update a table. My problem is that after submitting a fresh record I'm unable to update the first time (it shows blank), but the second time it works fine.
One more thing: when I remove the include statement then it is working fine on submessage.php there is no any phpcode. [annakata: I have no idea what this means]
$pid = $_GET['id'];
$title = $_POST['title'];
$summary = $_POST['summary'];
$content = $_POST['content'];
$catid = $_POST['cid'];
$author = $_POST['author'];
$keyword = $_POST['keyword'];
$result1= mysql_query("update listing set catid='$catid',title='$title',
summary='$summary',content='$content', author='$author', keyword='$keyword' where pid='$pid'",$db);
include("submessage.php");
The things that are wrong with that piece of code are hard to enumerate. However, at the very least, you should establish a connection to the database before you can query it.
Why not just redirect to submessage.php rather than inlining it? Redirecting also prevents duplicate db operations when user refreshed the page. Just replace include statement with:
header('Location: submessage.php?id=' . $pid);
die();
Also, before you deploy your application: DO NOT EVER PUT USER INPUT DIRECTLY IN SQL QUERY. You should used bound parameters instead. Otherwise, you could just as well publicly advertise your database admin password. Read more on PDO and prepared statements at http://ie.php.net/pdo
Here's how I would do it:
$pdo = new PDO(....); // some configuration parameters needed
$sql = "
UPDATE listing SET
catid=:catid, title=:title, summary=:summary,
content=:content, author=:author, keyword=:keyword
WHERE pid=:pid
";
$stmt = $pdo->prepare($sql);
$stmt->bindValue('catid', $_POST['catid']);
$stmt->bindValue('title', $_POST['title']);
$stmt->bindValue('summary', $_POST['summary']);
$stmt->bindValue('content', $_POST['content']);
$stmt->bindValue('author', $_POST['author']);
$stmt->bindValue('keyword', $_POST['keyword']);
$stmt->bindValue('pid', $pid = $_GET['id']);
$stmt->execute();
header('Location: submessage.php?id=' . $pid);
die();
Or in fact, I would use some ORM solution to make it look more like that:
$listing = Listing::getById($pid = $_GET['id']);
$listing->populate($_POST);
$listing->save();
header('Location: submessage.php?id=' . $pid);
die();
Other than the usual warnings of SQL injection - very likely given your code and where you're obtaining the query parameters from (sans any kind of validation) - then it's quite possible your problem has nothing to do with the queries, particularly if it's working on subsequent attempts. Are you sure $_GET['id'] is set the first time you call the script?
Just to note, there is absolutely no reason to have to perform several update queries for each field you need to update - just combine them into a single query.