So i want to check if a post exists in the database but i have some problems with redirection.
This is my work so far:
echo '<br>';//the $row part tells the DB what post his looking on
echo 'View comments';
This is the show comment button that leads to the section where you see the comments for the post.
<?php
require_once ('checkp.php');
I have it to require the post checking script once.
<?php
include ('variables.php');
//connects to DB
$dbc=mysql_connect($host,$user,$pass);
if ($dbc) {
} else {
echo ('Failed to connect to MySql; '. mysql_error());
}
//selects db from MySQl
$sqldb=mysql_select_db('a2318052_blog');
$pid=$_GET['post_id'];
$query1="SELECT * FROM posts_b WHERE id='$pid'";
$sql=mysql_query($query);
if ($sql) {
} else {
echo "cant run query";
}
if (mysql_num_rows($sql) > 0) {
echo "that post does not exist!";
} else {
header ("location: comments.php?post_id='. $pid.'");
}
?>
And this is the script that checks for a empty result and then redirects back. I believe its something with the redirect here (header ("location: comments.php?post_id='. $pid.'");)
You mixed the quotes on the redirect:
"location: comments.php?post_id='. $pid.'"
should be
"location: comments.php?post_id=". $pid
The dot in php is used to concatenate strings. Bu there you are opening the string with " and closing it with '.
EDIT : Also as someone else already noticed you're using query instead of query1.
Also i suppose instead of:
if (mysql_num_rows($sql) > 0) {
echo "that post does not exist!";
you wanted something else:
if (mysql_num_rows($sql) == 0) {
echo "that post does not exist!";
You probably don't want single quotes around the post_id...
header ("location: comments.php?post_id=$pid");
first change pid
$pid = intval($_GET['post_id']); // for security
after that
if (mysql_num_rows($sql) == 0)
{
echo "that post does not exist!";
}
else
{
header("Location: comments.php?post_id=".$pid);
}
$query1="SELECT * FROM posts_b WHERE id='$pid'";
$sql=mysql_query($query);
You're using $query instead of $query1. That's probably the problem (along with the concatenation stuff other users have pointed out).
There's also a few other things, like I think you mixed up your if/else statement here:
if (mysql_num_rows($sql) > 0) {
echo "that post does not exist!";
} else {
header ("location: comments.php?post_id='. $pid.'");
}
Maybe you want the order to be reversed?
Also, you should look into avoiding SQL injection!
Sending a query with a $GET variable is pretty dangerous, as users can manipulate the URL and send malicious queries.
$pid=$_GET['post_id'];
Prepared statements are ideal, but for now, you could use mysql_real_escape_string around your $GET variable. It stops people from sending queries you really don't want done.
Related
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.
After getting the user-info from my sql database I would like to check if some of the fields are empty and continue the script based on that. A simplified piece of code would look like this:
$userData = mysql_query("SELECT * FROM user WHERE user='".$user."' LIMIT 1");
if(mysql_num_rows($data) == 1){
$u_info = mysql_fetch_assoc($data);
if(empty($u_info['u_mobile'])){
echo 2;
exit();
} else {
echo 1;
exit();
}
} else {
echo 3;
exit();
}
The problem is the empty statement checking the recieved field. I've tried using empty(), isset(), not_null() and array_key_exists() with no luck and can't get around to what I'm doing wrong.
I also tried if($u_info['u_mobile']) == '' || $u_info['u_mobile']) == NULL) but that doesnæt work either.
Why is this, or how can I go about getting this information?
I need to collect the user-information and send them to fill out the information I don't have...
You're setting the query result to $userData but then you're using mysql_fetch_assoc($data); -- doh. You need to pass the variable that you set the query result to:
$u_info = mysql_fetch_assoc($userData);
It's OK, it is still 10AM EST so this can happen in the morning =)
I suggest that you turn on PHP error reporting. PHP would have alerted you that the array values were trying to access do not exist, saving you a lot of wasted frustration.
$userData = mysql_query("SELECT * FROM user WHERE user='".$user."' LIMIT 1");
if(mysql_num_rows($userData ) == 1){
$u_info = mysql_fetch_assoc($userData );
if(empty($u_info['u_mobile'])){
echo 2;
exit();
} else {
echo 1;
exit();
}
} else {
echo 3;
exit();
}
Please Run code..I think it will be compile better it was minor mistake
This is my first topic so far in this great webpage
The problem is this:
I'm scripting an UCP (PHP & MySQL based). I want it to show the user's status like score, money, etc. (Yeah, it's for a game) but when I click on the login button nothing happens it just erases the content of the requested fields.
It was working properly before I made some changes (Checking if the username exists)
Here's the code:
if (isset($_POST['login']))
{
$hashedpass = hash('whirlpool', $password);
$query = "SELECT * FROM users WHERE Username = '$playername' AND Password = '$hashedpass'";
$result = mysql_query($query);
$num = mysql_num_rows($result);
mysql_close();
if($num != 0)
{
echo"Account doesn't exist!";
header("Location: ucp.html");
}
else
{
$name=mysql_result($result,$i,"UserName");
$money=mysql_result($result,$i,"Money");
$score=mysql_result($result,$i,"Score");
$wantedlevel=mysql_result($result,$i,"WantedLevel");
$adminlevel=mysql_result($result,$i,"AdminLevel");
echo "<b>$name</b><br>Money: $money<br>Score: $score<br>Wanted Level: $wantedlevel<br>Admin Level: $adminlevel<br><br>";
}
}
else if (isset($_POST['register']))
{
header("Location: register.html");
}
else
{
header("Location: index.html");
}
if($num != 0)
change to:
if($num == 0)
This simply won't work here nor does it make much logical sense:
$num = mysql_num_rows($result);
mysql_close();
if($num != 0)
{
echo"Account doesn't exist!";
header("Location: ucp.html");
}
First the logic is wrong, if $num is NOT equal to 0 then your query MUST have found at least one account. So you need to change your if statement to:
if($num == 0){ //if 0 rows were found - the account was not found thus it doesn't exist
echo "Account doesn't exist!";
}
Notice also i did not add header("location: ucp.html");. You cannot display output + relocate the user to another page. You either do one or the other, or you will get an error/warning.
Finally check your MYSQL is not causing an error by adding a check at the end with :
$result = mysql_query($query) or die(mysql_error());
Final tip, you should avoid using mysql_* and look into mysqli_* or PDO best explained here:
Why shouldn't I use mysql_* functions in PHP?
I have a php script, with if and else blocks. Both contain echo statements only. The if block executes perfectly but when the else block executes nothing at all is printed to screen (not even the echo statements OUTSIDE the blocks). I have tried many things such as capitalising the ELSE statement, checking all the braces are there, double and triple checking the syntax to no avail. Please help.
<?php
// Inialize session
session_start();
// Include database connection settings
include('config.inc');
$usr = mysql_real_escape_string($_POST['****ID']);
// Retrieve email address and message from database according to user's input
$query = "SELECT * FROM users WHERE username = '$usr'";
$result = mysql_query($query) or die(mysql_error());
// Put the id numbers in array $row
$row = mysql_fetch_array($result) or die(mysql_error());
// Test for ID match
if (mysql_num_rows($result) == 1)
{
echo 'The email address of ';
echo $usr;
echo ' is: ';
echo $row['email'];
echo '<p>Message: ';
echo $row['firstname'];
}
else
{
echo 'Sorry it appears that ';
echo '$usr';
echo ' has not registered yet. Why dont you tell him about ****Jacker?';
}
// Executing outside if..else blocks for testing
echo 'Sorry, it appears that ';
echo '$usr';
echo ' has not registered yet. Why dont you tell him about ****Jacker?';
?>
You will have an error in
$row = mysql_fetch_array($result) or die(mysql_error());
Since the number of results is zero, your script will print a warning. Depending on your configuration, it's possible you see a white-page in stead of the warning.
Please note the
or die(..)
part.
Since the first part failed (fetching an empty result), the script will die and stop. No code lower than this line will be executed, so no logs, no if, ...
Best solution is to put the fetch_array inside the if (mysql_num_rows(..) == 1 statement, so we are sure there is at least 1 user to fetch