hello im trying to set custom errors. i got a form. actions to post.php i dont want form to go post.php for errors i need to set errors in same page. i tried
$sql = "
INSERT INTO yazilar (baslik, spot, spot_kisa, spot_resim, spot_resim_isim, icerik, kategori, tiklanma, eklemetarihi)
VALUES
('$_POST[baslik]','$_POST[spot]','$_POST[spot_kisa]','$_POST[spot_resim]','$_POST[spot_resim_isim]','$_POST[icerik]','$_POST[kategori]','$_POST[tiklanma]','$_POST[tarih]')
";
$sonuc = mysql_query($sql);
<?
if ($sonuc) {
echo ("<p class='msg done'>Yeni icerik basarili bir sekilde eklendi.</p>");
}
if(! $sonuc) {
echo ("<p class='msg warning'>Ekleme basarisiz oldu.</p>");
}
?>
this always shows Yeni icerik basarili bir sekilde eklendi. this.
help me plx
Your query is valid and it inserts data sucsesfully, therefore MySql_Query() returns true, which in turn "triggers" the first if, but not the second.
See documentation for return values of MySql_Query.
If you want validation you have to write it.
also: your two if statements can be refactored into one. Look at the if/else syntax
If you're trying to have your errors show up in the submitting form just move your post.php code into your form page and condition it like this:
<?php
if(isset($_POST['baslik'])) {
$sql = "
INSERT INTO yazilar (baslik, spot, spot_kisa, spot_resim, spot_resim_isim, icerik, kategori, tiklanma, eklemetarihi)
VALUES
('$_POST[baslik]','$_POST[spot]','$_POST[spot_kisa]','$_POST[spot_resim]','$_POST[spot_resim_isim]','$_POST[icerik]','$_POST[kategori]','$_POST[tiklanma]','$_POST[tarih]')
";
$sonuc = mysql_query($sql);
if ($sonuc) {
echo ("<p class='msg done'>Yeni icerik basarili bir sekilde eklendi.</p>");
exit;
}
else {
$error = "<p class='msg warning'>Ekleme basarisiz oldu.</p>";
}
}
?>
// form code here
<?php if(isset($error)) { echo $error; } ?>
// around where you'd like the error to display
Now if the action is a success the success message will display with nothing else, otherwise the form will be redisplayed with the error message where you positioned it. Also, please see soulmerge's comments on SQL injection, it's a serious security risk that can be easily avoided.
replace
$sonuc = mysql_query($sql);
with this
$sonuc = mysql_query($sql) or die(mysql_error());
is there any errors?
is it possible that your table fields do not match that ones you insert?
What is wrong about it? The return values of mysql_query() is a boolen for INSERT queries, which is true if the operation was successful. Have you tried inserting invalid values (like a text that is too long)? That should generate a warning and return false.
But what bothers much more is that your code is vulnerable to SQL injection. Please read up on sql injections on php.net how to fix that problem.
try this
$sonuc = mysql_query($sql);
<?php
if($sonuc !== false){
echo ("<p class='msg done'>Yeni icerik basarili bir sekilde eklendi.</p>");
} else {
echo ("<p class='msg warning'>Ekleme basarisiz oldu.</p>");
}
?>
EDIT: When you need a validation instead of a check if the query worked check this http://www.php-mysql-tutorial.com/wikis/php-tutorial/form-validation-using-php.aspx
Try this:
if ($sonuc !== false){...
See php manual entry
Jan Hančič has already answered the question but as a side note:
Don't use POST data directly on your queries it will end badly trust me!!
Related
I am still learing PHP and MySQLI and was wondering if it is possible to host multiple MySQLI delete queries on a single php page and have the url act on the corresponding query without confusion. I have this code here, I have search the web for an answer for 3 days but nothing I found seemed to be what I was looking for. Any help or properly described examples based on my code would be greatly appreciated.
my Code is:
<?php
session_start();
include ('dbconnect.php');
$userr = $_SESSION['usr_id'];
$uid=$_GET['pid'];
$pid=$_GET['phid'];
$user_id=$_GET['user'];
$fileID=$_GET['file'];
if($userr==$uid && $pid==$fileID){
echo "ERROR No. 9B2AP";
}else{
mysqli_query($con,"delete from images where userID='$uid' AND PhotoID='$pid'") or die (mysqli_error());
header ("location: /viewImage.php?pid=$uid");
}
if($userr==$user_id && $fileID==$pid){
echo "ERROR No. 39V41";
}else{
mysqli_query($con,"delete from music where userID='$user_id' AND Record_ID='$fileID'") or die (mysqli_error());
header ("location: /users/music-gallery/$user_id");
}
?>
No matter how many times I rewrite this code, when i delete an image or song using the code on this page, It redirects me only to the /users/music-gallery/ instead of the proper associated page. How might I get this fixed? Like I said, I am fairy new to PHP and MySQLI and any suggestions I believe should be described in details so I might be able to understand and comprehend how I made the mistake and I to fix and prevent it from happening again in later code. Please and Thank-you.
-M.S
For security reasons don't do this:
// Consider escaping the incoming data for better security
$uid=$_GET['pid'];
$pid=$_GET['phid'];
// ...
Since you are using MySQLi you can use this to escape your data:
$uid = mysqli_real_escape_string($con, $_GET['pid']);
You can use FILTERS to check input data type:
// If you are expecting an `INT` from $_GET['pid']
if (filter_var($_GET['pid'], FILTER_VALIDATE_INT))
{
echo 'pid is an int';
}
else
{
echo 'pid is not an int';
}
more on filters here.
The best of all, use prepared mysqli statements with stmt:
// prepare the statement
$stmt = $con->prepare("delete from images where userID=? AND PhotoID=?");
// bind variables to the '?' and set types --> `i` = integer
$stmt->bind_param("ii", $_GET['pid'], $_GET['phid']);
// execute query
$stmt->execute();
// Do the same for the next query
more on prepared statements here.
To solve your problem:
To exit a program right after a header you need to use exit(); after each header like this:
header ("location: /viewImage.php?pid=$uid");
exit();
For instance:
header ("location: /viewImage.php?pid=$uid");
// this line of code gets exucuted
// this too
// ...
header ("location: /viewImage.php?pid=$uid");
exit();
// Nothing gets executed as program terminates and redirects
I'm trying to use PHP to enter data from a form. When I try to enter duplicate data a bad message pops like
Something went wrong with this:
INSERT INTO customer VALUES('jamie9422','Jamie Lannister','sept of baelor','jamie#cersei.com',9422222222,0) Duplicate entry 'jamie9422' for key 'PRIMARY' "
Instead, I want to display a clean error message. How can I do that. Here's my code I've written so far...
<?php
include_once "dbConnect.php";
$connection=connectDB();
if(!$connection)
{
die("Couldn't connect to the database");
}
$tempEmail = strpos("{$_POST["email"]}","#");
$customer_id=substr("{$_POST["email"]}",0,$tempEmail).substr("{$_POST["phone"]}",0,4);
//$result=mysqli_query($connection,"select customer_id from customer where customer_id='$customer_id' ");
//echo "customer_id is".$result;
$query = "SELECT * FROM CUSTOMER WHERE CUSTOMER_ID='$customer_id'";
$customer_idcip = $customer_id-1;
echo $customer_idcip;
if ( mysql_query($query)) {
echo "It seems that user is already registered";
} else {
$command = "INSERT INTO customer VALUES('{$customer_id}','{$_POST["name"]}','{$_POST["address"]}','{$_POST["email"]}',{$_POST["phone"]},0)";
$res =$connection->query($command);
if(!$res){
die("<br>Something went wrong with this:{$command}\n{$connection->error}");
}
echo "Welcome ".$_POST["name"]." \nCongratulations on successful Registration. Refill your Wallet here";
//$cutomerRetrival = mysql_query("select from customer where customer_id='$customer_id'");
echo "<br>Please note your customer ID :".$customer_id;
}
/*if($result)
{
echo "Query Fired";
$dupentry = mysqli_num_rows($result);
if($dupentry==1)
{
echo "You are already Registered";
exit;
}
}*/
?>
The error code (number) is 1022.
You can e.g. define a constant for that (so that somebody else in x months has a chance to understand the code) like
define('ER_DUP_KEY', 1022);
and then do something like
if(!$res){
if ( <error code>==ER_DUP_KEY ) {
handleDuplicateEntryError();
}
else {
die("<br>Something went wrong with this:{$command}\n{$connection->error}");
}
}
since I don't know how $res =$connection->query($command); works (and what $connection is I can't tell you exactly how to implement <error code>==ER_DUP_KEY, could be by using mysql_errno.
But it seems to be somehow intermingled with mysql_query($query), i.e. the old, deprecated mysql_* extension and some custom class. You might want to fix that first.... ;-)
see http://docs.php.net/manual/en/mysqlinfo.api.choosing.php
Your code doesn't check for existing record properly
Change
if (mysql_query($query)) {
echo "It seems that user is already registered";
}
to
$result = mysql_query($query);
if (mysql_num_rows($result)) {
echo "It seems that user is already registered";
}
Also, PLEASE do not use $_POST variables without escaping them first, use something like mysql_real_escape_string() to escape each variable passed from the user, otherwise your website will be hacked really fast with SQL Injection.
Make some update into your and then try to get error message 'customer already registered.'
$query = "SELECT * FROM CUSTOMER WHERE CUSTOMER_ID='$customer_id'";
$res= mysql_query($query);
$customer_count = mysql_num_rows($res);
$customer_idcip = $customer_id-1;
echo $customer_idcip;
if ( $customer_count > 0 ) {
echo "It seems that user is already registered";
} else {
...................................
Thank you all.
Actually I was using mysqli API in my connectDB.php file..
Hence I needed to call functions on mysqli.
Instead I was calling mysql. i.e I was creating a new connection, thus the query wasn't getting fired at all.
Changed to mysqli->query($result) that is object oriented style
and it worked fine....
Use Try Catch instead.
try{
$res =$connection->query($command);
}catch(Exception $e){
die( "Write your error appropriate message here");
}
I have a simple registration form that inserts data into MySQL table. I am checking for error as well but it results in SUCCESS echo.
On Stackoverflow, I looked for the question, but couldn't really find an answer pertaining to my situation. Please forgive me if it has been answered. If it has been answered already, please provide a link and I will apologize for wasting anybody's time. Thank you! Below is my code:
<?php
if($_GET["regname"] && $_GET["regpass1"] && $_GET["regpass2"])
{
if($_GET["regpass1"]==$_GET["regpass2"])
{
$servername="localhost";
$username="root";
$password='';
$conn= mysql_connect($servername,$username,$password)or die(mysql_error());
mysql_select_db("test")or die("cannot select DB");
$sql="INSERT INTO members('id','username','password')VALUES('DEFAULT','$_GET[regname]','$_GET[regpass1]')";
if($sql)
{
echo "Success";
}
else
{
echo "Error";
}
print "<h1>you have registered sucessfully</h1>";
print "<a href='main_login.php'>go to login page</a>";
}
else print "passwords doesnt match";
}
else print"invaild data";
?>
You are checking if $sql exists. $sql is your actual query string. In this case, of course it will show it exists. Secondly, please do not use mysql_* for new code as it is deprecated. Instead use mysqli_* or PDO.
You actually haven't executed your query in your code. (Using deprecated mysql_* which is ill advised) the code as follows should execute the query:
$result = mysql_query($sql, $conn);
if($result == true)
echo 'Success';
else
echo 'Failure';
Instead of using the code above, I would strongly recommend updating your current code to use mysqli_* or PDO forms. You can read up more on this topic at the manpages linked previously.
Look at these lines:
$sql="INSERT INTO members('id','username','password')VALUES('DEFAULT','$_GET[regname]','$_GET[regpass1]')";
if($sql)
{
echo "Success";
}
You have created a request in $sql variable but have not executed it. The variable itself is non-empty, non-false so it evaluates to TRUE in the if-condition.
You should do it like this:
$sql="INSERT INTO members('id','username','password')VALUES('DEFAULT','$_GET[regname]','$_GET[regpass1]')";
$result = mysql_query($sql);
if (!$result)
{
die('Invalid query: ' . mysql_error());
}
else
{
echo "Success";
}
Just to be on the safe side I'll note that using variables from $_GET request like this, unfiltered, is an inapprorpiate tactic as it will lead to SQL injections, but I suppose you simplified code sample for the sake of brevity.
I am trying to insert a record into my database. here is my php code for doing that:
mysql_query("INSERT INTO answers(answer)
VALUES('answer')");
if(mysql_affected_rows() > 0) {
echo "Reply successful!";
} else {
echo "We were not able to add your reply.";
exit();
}
i made sure that i am connected to my db. i tried this on another page where i knew my sql would run, and it still didn't insert the record...
add
echo mysql_error();
to see the problem
Try passing $answer instead of answer. Also you should read up on SQL injection.
I've got an payment provider, which helps me to pay by call. However after the payment I need to UPDATE the order's status. This doesn't work. The whole script is found below.
if ($m->payed) {
$order_result = mysql_query('UPDATE jos_vm_orders SET order_status="C" WHERE order_id="'.$_GET['id'].'"');
echo '<b>Bedankt voor je betaling</b><br />
De betaling is succesvol gelukt!';
}
else {
$GET_['id'] is sent with the url.
I really don't know the answer, because the UPDATE line does work when I use it in the beginning (before the payment).
And not only the update line doesn't work, everything after 'if payed' doesn't work.
Thanks in advanced!
Examine the query:
$order_result = mysql_query('UPDATE jos_vm_orders SET order_status="C"
WHERE order_id="'.$_GET['id'].'"');
It is my guess that the WHERE clause is failing. Call mysql_affected_rows() after the operation; it will return 0 if no rows were updated.
The problem could also be the query failing. Wrap the query in a block similar to the following:
if (!$order_result = mysql_query('UPDATE jos_vm_orders SET order_status="C"
WHERE order_id="'.$_GET['id'].'"')) {
// Handle the error here.
}
Also note, it is not good practice to ever use $_GET or $_POST data directly in an SQL query. Consider validating it, at least by doing this:
$_GET['id'] = (int) $_GET['id'];
if ($_GET['id'] === 0) {
// handle the error here
}
Please verify the value of $m->payed by adding var_dump() in your code.
var_dump($m);
if ($m->payed)
{
$sql="UPDATE jos_vm_orders SET order_status='C' WHERE order_id=$_GET[id]";
$order_result = mysql_query($sql);
echo '<b>Bedankt voor je betaling</b><br />
De betaling is succesvol gelukt!';
}
You have to learn how to debug your code.
It's impossible to say what's the problem just by watching the code.
One have to run the code, get all possible error messages and check all important variables. that's the only way to find the problem.
So, to get possible error message you have to run your query the same way as previous one, by using mysql_error()
And also you must take care of the values going to the query.
So, make your code like this:
if ($m->payed) {
$id = intval($_GET['id']);
$sql = "UPDATE jos_vm_orders SET order_status='C' WHERE order_id=$id";
$res = mysql_query($sql);
if (!$res) {
trigger_error(mysql_error()." ".$sql);
echo '<br>Server Error<br>';
} elseif (!mysql_affected_rows($res)) {
trigger_error("No rows were updated! ".$sql);
echo '<br>Server Error<br>';
} else {
echo '<b>Bedankt voor je betaling</b><br />De betaling is succesvol gelukt!';
}
} else {
echo '<font color=red><b>Betaling is niet afgerond,<br />volg de onderstaande instructies!</b></font><br /><br />';
}
include('includes/include.paymentscreen.php');
}
The problem was eventually my server, I had 'display erros' on off. When I turned it on, the actually error lied with the session_start. When I opened the file on my server, I saw I saved it in the wrong format, this solved it!
Thanks for every answer.
Try Change This
UPDATE jos_vm_orders SET order_status="C" WHERE order_id="'.$_GET['id'].'"
To
$id=$_GET['id'];
"UPDATE jos_vm_orders SET order_status='C' WHERE order_id='$id'"
Be careful with quotes in query. Always Give Double quotes at starting and ending , prefer single quotes in the middle of query.
Avoid concatination in query and instead try including it like mentioned above