I want to be able to add and update certain information. Now it was all working fine untill I found out the script no longer works when there's quotation marks in the text being sent to the database.
So I've done some research and found out I had to use the mysql_real_escape_string() function to ignore the quotation marks. I've done this but the script now isn't working at all anymore. I think the problem lies in the query part but i don't see the problem. Below is the code:
<?php
if(isset($_POST['bevestiging']))
{
$ID = (int)$_GET['ID'];
$titel = mysql_real_escape_string($_POST['Titel']);
$ondertitel = mysql_real_escape_string($_POST['ondertitel']);
$wanneer = mysql_real_escape_string($_POST['wanneer']);
$datum = mysql_real_escape_string($_POST['datum']);
$afbeelding = mysql_real_escape_string($_POST['afbeelding']);
$intro = mysql_real_escape_string($_POST['intro']);
$main = mysql_real_escape_string($_POST['main']);
$query = "UPDATE voorstellingen
SET '$titel','$ondertitel','$wanneer','$datum','$afbeelding','$intro','$main'
WHERE id = $ID";
mysql_query($query) or die('Error, bewerken van voorstelling is mislukt');
$query ="FLUSH PRIVILEGES";
echo"De voorstelling is succesvol bewerkt";
}
else{
$ID = (int)$_GET['ID'];
$query="SELECT * FROM voorstellingen WHERE id = $ID";
$result = mysql_query($query) or die('Error, bewerken van voorstelling is mislukt');;
?>
your update query should be like:
$query = "UPDATE voorstellingen SET title = '".$titel."' .....";
See: UPDATE Syntax
mysql_real_escape_string function returns FALSE on errors. You can check the return type of the below line
$titel = mysql_real_escape_string($_POST['Titel']);
to see if it succeeds or not. You do not need to check the next lines. If there is error on first function call, it will very probably mean that no SQL connection is present before invoking the function. Because a MySQL connection is required before using mysql_real_escape_string() otherwise an error of level E_WARNING is generated, and FALSE is returned.
If the above suggestion does not solve your issue , please elaborate what error exactly are you facing and on which line.
Related
I am trying to insert rating in database and calling average of that given rating from database
<?PHP
$connection = mysqli_connect("localhost", "akdnaklnd", "lfnlfns","faknfns");
$game = $_POST['game'];
$post_rating = $_POST['rating'];
$find_data = mysqli_query( "SELECT * FROM rates WHERE game='$game'");
while($row = mysqli_fetch_assoc($find_data)){
$id=$row['id'];
$current_rating = $row['rating'];
$current_hits=$row['hits'];
}
$new_hits = $current_hits + 1;
$update_hits= mysqli_query("UPDATE rates SET hits = '$new_hits' WHERE id='$id'");
$pre_rating= $current_rating + $post_rating;
$new_rating = $pre_rating / $new_hits;
$update_rating = mysqli_query("UPDATE rates SET rating ='$new_rating' WHERE id='$id'");
header("location : average.php");
?>
try to debug it by removing all the MySQL stuffs from code and keep redirection code with no space ie .
header("location:average.php");
if it works then there must be an error on your MySQL query. try adding error check after execution each MySQL query operations. Hope that will help you finding the breakpoint where your execution terminates before redirection statement.
Add $connection param to mysqli_query like this:
$find_data = mysqli_query($connection, "SELECT * FROM rates WHERE game='$game'");
Delete space symbol after "location" before colon: header("location: average.php");
Firstly you need not to select data you can directly write your update query like this.
Please make sure you pass variable instead of string for better practise use double and single quotes and dott too.
Most important pass connection variable.
$update_hits= mysqli_query($connection,"UPDATE rates SET hits = hits+1 WHERE id='".$id."'");
Try echo $update_hits if it give one then query successful else there is issue.
For that you can use error log
if (!$result) {
$errorQuery = $update_hits;
throw new Exception(mysqli_error($connection));
$errorMessage = mysqli_real_escape_string($connection,$e->getMessage());
echo $errorMessage;
exit();
}
else{
echo "Success";
}
<?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
ok i am having a slight problem with my posting script. Everything works great except for when i type in a phrase with like an apostrophe, example "Here's my title" wont post, put "Heres my title" will post. Not sure why this is. Maybe the strip tags i really dont know, what should i do? When it doesnt work i get thet bottom error message
} else {
if(isset($_POST['what'])&&isset($_POST['when'])&&isset($_POST['where'])&&isset($_POST['details'])&&isset($_POST['sponsored_by'])&&isset($_POST['collegeId'])){
$what = nl2br(htmlspecialchars(strip_tags(stripslashes(trim($_POST['what'])))));
$where = nl2br(htmlspecialchars(strip_tags(stripslashes(trim($_POST['where'])))));
$when = nl2br(htmlspecialchars(strip_tags(stripslashes(trim($_POST['when'])))));
$sponsored_by = nl2br(htmlspecialchars(strip_tags(stripslashes(trim($_POST['sponsored_by'])))));
$details = nl2br(htmlspecialchars(strip_tags(stripslashes(trim($_POST['details'])))));
$collegeId = intval($_POST["collegeId"]);
if(isset($_SESSION['username'])){
$username = htmlspecialchars(strip_tags(stripslashes(trim(($_SESSION['username'])))));
$query = "select id, Name from users where username='$username' and activated = 1";
$doQuery = mysql_query($query);
if(mysql_num_rows($doQuery)>0){
$results = mysql_fetch_array($doQuery);
$userName = $results['Name'];
$email = $username;
$id = $results['id'];
$query = "insert into events values(NULL,$id,$collegeId,'$what','$when','$where','$details','$sponsored_by',NOW())";
if(mysql_query($query)) header("Location: collegeInfo.php?college=$collegeId&message=added");
else echo "Failed to create new Event!".$query;
U dont escape your query. Try to sanitize your inputs at least with addslashes or mysql_real_escape_string. So stripslashes - delete backslashes from line. Use addslashes to add them, instead of deleting before mysql query.
And dude, mysql_query is DEPRECATED in new php versions, please use PDO with prepared statements.
I have a little test project set up so that when you click a wolves's name, it takes them to a page that I want to use to personalize information concerning whichever wolf they clicked on. The page is called wolf.php. I'm trying to using passing variable the $_GET method to assign the URL the wolves id, i.e www.testsite.com/wolf.php?id=1 but the page then displays nothing even though I do not get an error.
Here's the home page (home.php)
<?php
$username = $_SESSION['username'];
$result = #mysql_query("SELECT * FROM wolves WHERE owner = '$username'");
while($wolf = mysql_fetch_array($result))
{
echo "<a href= wolf.php?id=$wolf[id]>$wolf[name]</a>";
};
?>
Clicking this link takes me to www.testsite.com/wolf.php?id=1 (or whatever the id was). On wolf.php I have this:
<?php
$id = $_GET['id'];
$result = #mysql_query("SELECT name FROM wolves WHERE id = '$id'") or die("Error: no
such wolf exists");
echo .$result['name'].
;
?>
I'm not sure where I went wrong but this doesn't seem to be working. No information regarding the id of the wolf shows up. Thanks for help in advance.
Turn on error reporting with error_reporting(E_ALL); ini_set('display_errors', 1); in development so you see the fatal syntax errors in your code. It is also recommended to remove # error suppression operator from your mysql_*() calls.
You have syntax problems on the last line. Unexpected . concatenation operators:
// Wrong:
// Parse error: syntax error, unexpected '.'
echo .$result['name'].
;
// Should be:
echo $result['name'];
Next, you have not fetched a row from your query:
// mysql_query() won't error if there are no rows found. Instead you have to check mysql_num_rows()
$result = mysql_query("SELECT name FROM wolves WHERE id = '$id'") or die("Query error: " . mysql_error());
// Zero rows found, echo error message.
if (mysql_num_rows($result) < 1) {
echo "No such wolf.";
}
else {
// Row found, fetch and display.
$row = mysql_fetch_assoc($result);
echo $row['name'];
}
Note that this script is wide open to SQL injection. At a minimum, call mysql_real_escape_string() on your query input variables.
$id = mysql_real_escape_string($_GET['id']);
Ultimately, think about using PDO or MySQLi instead of the old mysql_*() functions, as they support prepared statements for greater security over manually escaping variables. The mysql_*() functions are planned for deprecation.
Firstly need fetch a result row.
Variant 1 - associative array (values are avialable as field names)
$result = mysql_fetch_assoc($result);
echo $result['name'];
Variant 2 - enumerated array (by index, started from zero)
$result = mysql_fetch_row($result);
echo $result[0];
<?php
$username = $_SESSION['username'];
$result = #mysql_query("SELECT * FROM wolves WHERE owner = '$username'");
You forgot the session_start(); at the begining. $username is "" and the sql maybe is returning 0 records.
In your second snippet you can't treat $result like it's an array; it's a resource identifier. To get an array, do:
$row = mysql_fetch_assoc($result);
echo $row['name'];
Also read about SQL injection vulnerability.
I am validating a form (checking if field are empty etc and at the end I am using my last validation rule:
//Database Information
//Connect to database
mysql_connect($dbhost, $dbuser, $dbpass)or die("Could not connect: ".mysql_error());
mysql_select_db($dbname)or die(mysql_error());
$email = mysql_real_escape_string($_POST['email']);
$cust_code = mysql_real_escape_string($_POST['cust_code']);
//validation e.g.
if (empty($email) + empty($cust_code) > 1){
....
//if everything is ok
$sql = "SELECT * FROM clients WHERE ID='$cust_code'";
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0){
$data = mysql_num_rows($result);
//get all fields from db and do something
}else{
//My error that is showing up
echo "<span class=\"difftext\">The customer code you have entered is not valid!
<br />
Please enter a valid Customer Code to procceed!
</span>";
Is anything wrong with that because even if I enter the correct cust_code I am getting my error msg instead of my data...
Thank you
EDIT...(I removed, as it is wrong) AND YOU DID WELL... I JUST REALISE WHAT I DID... SORRY...
I have corrected it above.
Thank you
HOW TO DEBUG
Do not put the query string immediately into the mysql method, echo it first
$sql = "SELECT * FROM clients WHERE ID='$cust_code'";
echo $sql;
$res=mysql_query($sql);
Are you even connected to the DB?
Error messages are written in English (if it is not MS error messages). Why would you ignore them? Put the error message, read it, try to understand what it says.
An advice, if you will write code that way, it is ok for very small application, for big ones, you need to take a different approach completely to code organization. Which is one of the problems/main problem frameworks are trying to solve for you.
Actually, you are wrong, your error is here, in this two lines:
$sql = mysql_query("SELECT * FROM clients WHERE ID='$cust_code'");
$result = mysql_query($sql);
You are running the query twice.
After the first time $sql holds the resource, then you refer to the resource as if it was a query string. To fix it, change it to:
$sql = "SELECT * FROM clients WHERE ID='$cust_code'";
$result = mysql_query($sql);
You might have more underlying errors, but fix this one first.