Not inserting where i expected - php

In a mysql table, i have 3 fields. user_to, user_from and id. The variables are all correct and should be inserting the correct data.
When a button is clicked, named 'poke', it should insert the cookie that stores the session of who did it and the person who was poked. It doesn't seem to be inserting and I am stuck :(
$cookie = $_SESSION['user_login'];
//Poke code
if (#$_POST['poke']) {
$check_if_poked = mysql_query("SELECT * FROM pokes WHERE user_to='$username' && user_from='$added_by'");
$num_poke_found = mysql_num_rows($check_if_poked);
if ($num_poke_found == 1) {
echo "Come on! Give the guy a chance!";
}
else
if ($username == $cookie) {
echo "You cannot Jab yourself.";
}
else
{ $poke_user = mysql_query("INSERT INTO `pokes` ('user_from', 'user_to') VALUES ('$cookie', '$username')") or trigger_error(mysql_error());
echo "$username has been jabbed.";
}
}

You used wrong quotes with fields in MySQL query.
//your wrong variant
"INSERT INTO `pokes` ('user_from', 'user_to') VALUES ('$cookie', '$username')"
//right variant
"INSERT INTO `pokes` (`user_from`, `user_to`) VALUES ('$cookie', '$username')"
Quotes like ' mean values and quotes like ` mean fields in SQL syntax

<?php
if ($_POST['poke']) {
#ref to the current user
$from = $_SESSION['user_login'];
#ref to the (poked user)
$to = $_POST['poked_user_id'];
if($from == $to){
echo "you cant poke yourself!";
}
else{
#ADVICE: USE PDO OR MYSQLI INSTEAD OF MYSQL
$check_if_poked = mysql_query("SELECT * FROM pokes WHERE user_to='$to' AND user_from='$from'");
if(mysql_num_rows($check_if_poked)){
echo "Come on! Give the guy a chance!";
}
else{
if(mysql_query("INSERT INTO `pokes` (`user_from`, `user_to`) VALUES ('$from', '$to')")){
echo "$to has been jabbed.";
}
else{
trigger_error(mysql_error());
}
}
}
}
?>

This started off as a comment - but it's getting too long to fit.
A session is not the same thing as a username - your post is very confused.
Leaving aside the wrong quotes (which is why your code is not doing what you expect)....
In a mysql table, i have 3 fields. user_to, user_from and id
... in that case you don't need to check if the row already exists - and not create duplicates. Set up a unique index then...
if (#$_POST['poke'] && ($_SESSION['user_login']!===$username)) {
$qry = "INSERT INTO `pokes` (`user_from`, `user_to`)
VALUES (".mysql_real_escape_string($_SESSION['user_login'])
.", '" . mysql_real_escape_string($username) . "')"
if (mysql_query($qry)){
echo "$username has been jabbed.";
} else if (stristr(mysql_error(), 'duplicate')) {
echo "Come on! Give the guy a chance!";
} else {
echo "It's all gone Pete Tong!";
}
} else if ($_SESSION['user_login']!===$username) {
echo "You cannot Jab yourself.";
}
While it's about the same effort for PHP processing, the DB workload is significantly less. This code also prevents some SQL injection attacks, and has error handling. I presume that $username has been created elsewhere and you don't have register_globals enabled.

Related

PHP echo break tag

In my PHP script, there are 3 echo, based on the conditionals
echo "Error"
echo "User already existed"
echo "Success"
One of the echo will be passed to my android apps, if (s.equals("Success")), where s is the echo message.
But the echo I got when the registration success is <br />, according to the logcat. For User already existed have no problem.
Since s is not Success, I can't start another activity which is depended on the string. Can anyone explain how the break tag got echoed? The registration information successfully inserted into database, though.
elseif ($roleID == "C") {
$sql6 = "SELECT runnerID FROM tr_customer WHERE customerID = '$newID'";
$check4 = mysqli_fetch_array(mysqli_query($con,$sql6));
if(!isset($check4)) {
// add into db
$customerID = $roleID . $newID;
$sql7 = "INSERT INTO tr_customer(customerID, name, phoneNo, locationID, roleID, email) VALUES ('$customerID', '$name', '$phoneNo', '$locationID', '$roleID', '$email')";
if(mysqli_query($con,$sql7)) {
echo "Success";
}
} else {
$newID = checkExist();
}
I would examine the code where the variable is defined. If you could post that part of the code as an edit then perhaps someone can review it for you as well. There is just not enough information here to discern where your error is coming from.
EDIT:
Consider changing the way you check for a successful update.
$result = mysqli_query($con,$sql7);
if(mysqli_num_rows($result) == 1){
echo "Success";
}

Why is my else statment running the code twice

My code:
<?php
$name = $_POST["name"];
//establishing connection through PDO
require("database.php");
try{
//querying the firstname data from the people table
$sql = $conn->query("SELECT firstname FROM people");
}catch (Exception $e) {
echo "Data could not be retrieved from the database.";
exit;
}
//looping through the array of firstname and echoing it out if it equals to the user input of name. else just echo out sorry no match
while($theRow = $sql->fetch(PDO::FETCH_ASSOC)){
if(strtolower( $name ) == strtolower( $theRow["firstname"] ) && isset($_POST['name']) ){
echo $theRow['firstname'] . "<br />";
}else {
echo 'Sorry no match';
exit;
}
}
?>
the require database.php is just establishing connection to my database using PDO.
I just have 2 rows in my database with
'firstname' of
Jack
Bob
and if in my input field anyone types one of those 2 names php will echo out that name from the people table in the database. Very simple but the only problem I am having is on my else statement I wanted it to echo out Sorry no match if the input field of name is not equal to any name in the database. BUT instead it echo's out Sorry no match once for each name. I understand that I am looping through the array of database name but I only want it to echo Sorry no match once if the name input is not equal to a "firstname" in the database.
EXTRA NOTE:
I have also tried using a foreach loop instead of the while looping with the fetchAll method instead of just fetch but no luck there. Basically gave me the same results.
UPDATE ON THE PROBLEM:
When I load the page the else statement is already taking effect and
echoing out Sorry no match even before I set a name in the input.
and if I type the wrong name it ill echo out Sorry no match twice if
I type the correct name it will echo out the name out of the database
and Sorry no match once.
FIGURED IT OUT:
<?php
$name = $_POST["name"];
require("database.php");
try{
$sql = $conn->prepare("SELECT firstname FROM people WHERE firstname = ?");
$sql->bindParam(1,$name);
$sql->execute();
}catch (Exception $e) {
echo "Data could not be retrieved from the database.";
exit;
}
$theRow = $sql->fetch(PDO::FETCH_ASSOC);
if(strtolower( $name ) == strtolower( $theRow["firstname"] ) ){
echo $theRow['firstname'] . "<br />";
}else{
echo 'no match';
}
?>
Turns out I did not even need a loop do to the WHERE claus only getting the firstname that matched $_POST['name'] so it was just a matter of when to out put that data and that was when the if statement came in. But if I had to output more than one single data I would of probably used a foreach loop like so:
if(strtolower( $name ) == strtolower( $theRow["firstname"] ) ){
foreach( $theRow as $row ){
echo $row . "<br />";
}
}else{
echo 'no match';
}
If anyone sees any problem with this code or my method please do let me know. Thank you
Firstly, you seem to answer your own question: Why is the else statement running the code twice? Ans: it's not; it's running it once for each iteration of the loop, because you put it in the loop.
Just change your SQL to:
$stmt = $conn->prepare("SELECT firstname FROM people where firstname = ?");
$stmt->execute(array($name));
$result = $stmt->fetchAll();
And it'll either return 1 or 0 rows. So your if statement will look like this:
if($result->num_rows) // True if num_rows > 0; else false
And put your while loop inside your if statement. Keep your else statement to just echo 'Sorry no match';.

PHP Mysql Data Insert

I'm learning PHP from reading the php manual and studying different tutorials. I hit a snag with the mysql_query. I'm trying to insert user data into a database from a form using PHP. The mysql_query should return false because the username doesn't exist in the database yet but according to the result I am getting it is returning true and nothing is being entered into the database. Am I using mysql_query wrong or is using !result incorrect?
$sql = "SELECT * FROM users WHERE username='".$_POST["name"]."'";
$result = mysql_query($sql)
if (!$result) {
$sql = "INSERT INTO USERS (username, email, password) VALUES
('".$_POST["name"]."', '".$_POST["email"]."', '".$passwords[0]."')";
$result = mysql_query($sql);
if ($result) {
echo "It's entered!";
} else {
echo "There's been a problem: " . mysql_error();
}
} else {
echo "There's already a user with that name: <br />";
$sqlAll = "SELECT * FROM users";
$resultsAll = mysql_query($sqlAll);
$row = mysql_fetch_array($resultsAll);
while ($row) {
echo $row["username"]." -- ".$row["email"]."<br />";
$row = mysql_fetch_array($result);
}
}
Jason, you're checking to see if the query has failed or not - not whether it has returned the value 'false' or 'true'. You need to call mysql_fetch_row or similar, then compare the result.
Alternatively you could use the following:
if (mysql_num_rows($result) == 0) {
/* User doesn't exist */
} else {
/* User exists */
}
This will detect if any users have been chosen by your query and - if they have - your user exists already.
Also, you should learn about input sanitisation and SQL Injection. It's a very critical security issue and your script is vulnerable to it. More info here.
A select query which has no result rows STILL returns a result handle. msyql_query() will ONLY return a 'false' value if the query fails due to a syntax error, constraint violation, etc...
Your code should be
$sql = "...";
$result = mysql_query($sql);
if ($result === false) {
die("QUery failed: " . mysql_error());
}
if (mysql_num_rows($result) == 0) {
... user does not exist ...
}
And please please please read up about SQL injection vulnerabilities. Your code has holes wide enough for a truck to drive through.
In this case, $result will be a resource. You should check the number of results with mysql_num_rows().
Never, really, NEVER, use $_POST or any direct user input in a query. Always escape the input, BEFORE using it in a query, with mysql_real_escape_string(), or you'll have opened a serious security issue with SQL Injection.
Ex:
$safe_name = mysql_real_escape_string($_POST["name"]);
$sql = "SELECT * FROM users WHERE username='$safe_name'";
It's not exact.
mysql_query() will also fail and return FALSE if the user does not
have permission to access the table(s) referenced by the query.
In your case you have the permission but the user doesn't exist. So it will return true but the result set returned is empty.
mysql_query will return an empty set if the query returns no data. The query will however not fail.
i solve my problem :
like this
<?php
$username = $_POST['username'];
include('config.php');
$result = mysqli_query($con,"SELECT * FROM persons WHERE username='$username'");
while($row = mysqli_fetch_array($result)){
echo $row['username'];
echo "</br>";
echo "</br>";
echo "<p><b>Secret Question</b></p>";
echo $row['secret'];
}
?>
</br>
</br>
<form action="forgetaction.php" method="POST">
<p><b>Answer is :</b><p>
<input type="hidden" name="username" value="<?php echo $username; ?>">
<input type="text" name="answer">
</br>
</br>
<input type="Submit" value="Submit">
</form>
and forget action.php like this :
<?php
include('config.php');
$username = $_POST['username'];
echo $username;
$result = mysqli_query($con,"SELECT * FROM persons WHERE username='$username'");
$row = mysqli_fetch_array($result);
if($row['answer'] == $_POST['answer']) {
echo $row['password'];
} else {
echo 'wrong!';
}
?>
thank you all for help .

Insert data in multiple tables if a checkbox is checked

I am creating a user registration form with simple requirements.and insert data with simple query
<?php
if (isset($_POST) && isset($_POST["form_register"]))
{
$insert_query = "INSERT INTO users SET
users.first_name='" . mysql_real_escape_string($_POST['fname']) . "',
users.last_name='" . mysql_real_escape_string($_POST['lname']) . "',
users.email='" . mysql_real_escape_string($_POST['email']) . "',
users.password='" . mysql_real_escape_string($_POST['password']) . "';";
if (mysql_query($insert_query))
{
$_SESSION['messageType'] = "success_msg";
}
else
{
$_SESSION['message'] = "-Registration not Successful.";
$_SESSION['messageType'] = "error_msg";
}
}
?>
but now I have 3 extra fields in this form. If I select a checkbox then the other 2 field data go in another table with having this data also. how can i do that?
It is my old code...now I add 3 new columns, 1 checkbox and 2 text boxes.
The query is, if checkbox is selected then other 2 colums values go in another table and if checkbox is not select then working 1 query.
If I understand right you want to insert data in another table IF user check the checkbox.
So you have to use another IF like this:
if (mysql_query($insert_query))
{
if (/* here your condition for checkbox*/)
{
/* here your query for the secund table and the new two values*/
}
$_SESSION['messageType'] = "success_msg";
}
Note that is extremely important you run the secund query after the success of the first, cause if the first fails for some reason, secund will not be executed.
We really need to see your form as what you're providing us is way too vague, also, check the ending syntax for your $insert_query.
If I comprehended the question right, the final code should look something like this.
Tell me if I'm wrong
<?php
if(isset($_POST) && isset ($_POST["form_register"])){
$insert_query1 = "INSERT INTO users SET
first_name='".mysql_real_escape_string($_POST['fname'])."',
last_name='".mysql_real_escape_string($_POST['lname'])."',
email='".mysql_real_escape_string($_POST['email'])."',
password='".mysql_real_escape_string($_POST['password'])."'";
if(mysql_query($insert_query)){
$_SESSION['messageType'] = "success_msg";
} else {
$_SESSION['message'] = "-Registration not Successful.";
$_SESSION['messageType'] = "error_msg";
}
if($_POST['checkbox']) {
$insert_query2 = ""; //Put your second MYSQL Query here
}
if(mysql_query($insert_query2)){
$_SESSION['messageType2'] = "success_msg";
} else {
$_SESSION['message2'] = "-Registration not Successful.";
$_SESSION['messageType2'] = "error_msg";
}
}
?>

PHP - $GET and delete from MySQL

I have an a href which looks like that: Delete
And file delete-news.php is as follow:
<?php
if(isset($_GET["?deleteID='.$id."]))
{
$result = mysql_query("DELETE FROM 'news' WHERE id='$id'");
echo mysql_error();
if($result)
echo "succces";
}
else { echo "GET NOT SET"; }
?>
But it is returning GET NOT SET. What I'm doing wrong?
Use this, and for god's sake escape your inputs.
if(isset($_GET['deleteID'])) {
$result = mysql_query("DELETE FROM `news` WHERE id='".mysql_real_escape_string($_GET['deleteID']). "'");
echo mysql_error();
if($result)
echo "succces";
} else {
echo 'GET NOT SET';
}
$_GET will have each element of the GET variables already broken down, so no need to include the URL data. So, in your example, the link ?deleteID=123 would produce $_GET['deleteID'].
Try using that, but also remember to sanitize the values you receive in from URLs. If it's going to be a numeric value, I suggest casting it:
$deleteID = (int)$_GET['deleteID'];
Please also note that changes to the system should only happen via POST, and never GET. Otherwise (for example), you might get a spidering bot that deletes your whole site. See this post for more references:
https://stackoverflow.com/questions/679013/get-vs-post-best-practices
You need to check $_GET for just deleteID. Later, reference it as $_GET['deleteID']. Also, call mysql_real_escape_string() on $_GET['deleteID'] to retrieve your query parameter $id.
if(isset($_GET["deleteID"]))
{
$id = mysql_real_escape_string($_GET['deleteID']);
$result = mysql_query("DELETE FROM `news` WHERE id='$id'");
echo mysql_error();
if($result)
echo "succces";
}
else { echo "GET NOT SET"; }
Try this instead:
<?php
if(isset($_GET['deleteID']))
{
$id = intval($_GET['deleteID']);
$result = mysql_query("DELETE FROM `news` WHERE id='$id'");
echo mysql_error();
if($result) echo "succces";
} else {
echo "GET NOT SET";
}
?>
Note that I'm making the given deleteID into an int, meaning that values other than some form of number will become 0.
Also, you can't wrap a table- and/or column name with ' - backticks are the way to go!
<?php
if(isset($_GET["deleteID"]))
{
$id = ($_GET['deleteID']);
$result = mysql_query("DELETE FROM news WHERE id='".mysql_real_escape_string($id)."'");
echo mysql_error();
if($result)
echo "succces";
}
else { echo "GET NOT SET"; }
?>
is correct one
You obtain GET NO SET, because the $_GET associative array does not contain ?deleteID='.$id.
In order for you to obtain the id, you need to so something like this:
$id = $_GET['deleteID'];
Also
$result = mysql_query("DELETE FROM 'news' WHERE id='$id'");
That is very unsafe as it allows SQL injections. Instead, do:
$query = sprintf("DELETE * FROM news WHERE id=%d",
mysql_real_escape_string($id),
$result = mysql_query($query);
I hope this helped.

Categories