I've been working for the past 5 hours on why does this if get triggered...
Let me show you the code and explain you :
<?php
require_once "ConnectDB.php";
$link2 = $link;
$key = $posthwid = "";
$err = "";
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(empty($_POST["key"])){
$err = "Thanks for the ip (" .$_SERVER['REMOTE_ADDR']. "), have a good day! (1)";
}
else{
$key = trim($_POST["key"]);
}
$hwid = $_POST["hwid"];
if(empty($err)){
$sql = "SELECT hwid, idkey, length, created_at FROM money WHERE idkey = '" .$key. "'";
$row = mysqli_query($link, $sql);
if(mysqli_num_rows($row) < 2){
while($result = mysqli_fetch_assoc($row)) {
if($result["idkey"] == $key)
{
$err = "key";
if($result["hwid"] == "")
{
$err = "nohwid";
$sql2 = "UPDATE IceCold SET hwid = '" .$hwid. "' WHERE idkey = '" .$key. "'";
if(mysqli_query($link2, $sql2)){
$hwid = $result["hwid"];
mysqli_close($link2);
echo "debug";
}
else {
$err = "Oops! Something went wrong. Contact the support.";
}
}
if ($hwid !== $result["hwid"]) {
$err = "Contact the support";
}
elseif($_SESSION["admin"] == true) {
//Do special stuff
}
else {
///do other checks
if($created_at > $date){
$err = $hwid;
} else {
$err = "The key date is too old, buy a new one.";
}
}
}
else{
$err = "The key you entered was not valid.";
}
} mysqli_close($link);
} else {
$err = "multiple entry, contact support";
}
}
} else {
$err = "Thanks for the ip (" .$_SERVER['REMOTE_ADDR']. "), have a good day! (3)";
}
echo $err;
?>
So basically, I have this Connect DB file with a mysqli_connect called $link and I'm designing a liscence API for my program. My program will send a request with the "idkey" and "hwid" and is waiting for the hwid to come back. I have an entry in my sql databse with only a key registered and I've trying to make my program wotk by generating POST request with the id and a random hwid but I've found no success. If variables are weirdly moved around, It's because of the debugging.
Right now, with my current setup, I get the Contact the support response which I don't understand why?!? The request and the key are correct if I'm able to get this awnser.
It's probably a stupid mistake but I jsut can't figure it out...
Thanks in advance for your help
Edit: the if statement I'm referring to is this:
if($hwid !== $result["hwid"])
There was a typo in the code that I fixed but it wasn't the issue,
as for the elseif, that would destroy the order of execution of the code and destroy the logic behind it(If that made sense).
Weirdly, after some tests, I found out that the second SQL request I send doesn't want to be executed ($sql2) and there is no error in httpd logs... Can you execute two requests? I tried to create $link2 but it doesn't change anything
EDIT : Found solution
if($result["hwid"] == "")
{
$sql2 = "UPDATE money SET hwid = '" .$_POST["hwid"]. "' WHERE idkey = '" .$key. "'";
if(mysqli_query($link2, $sql2)) {
$newhwid = $_POST["hwid"];
mysqli_close($link2);
}
else {
$err = "Oops! Something went wrong. Contact the support.";
}
}
elseif ($_POST["hwid"] != $result["hwid"]) {
$err = "Contact the support";
}
if($_POST["hwid"] == $newhwid || $_POST["hwid"] == $result["hwid"] ) {
/// do other checks
}
The condition before that one, if($row['hwid'] = ""), is an assignment. This code is changing the value of $row['hwid'] to an empty string, causing the condition after it to be true. I assume you meant to write == to test if $row['hwid'] is empty; otherwise it doesn't make sense to write this as an if statement.
By the way, it's not clear whether this if statement shouldn't be an else if. The rest of the branches here are else if (or elseif, which is the same in PHP), so you should consider whether you have missed out an else on this one too.
Related
The data is not inserting into another table, here's the code below :
if (isset($_POST))
{
$job = $_POST['jobtitle'];
$dur = $_POST['duration'];
$deg = $_POST['requireddegree'];
$exp = $_POST['experiance'];
$sal = $_POST['salary'];
$mark = $_POST['marks'];
if ( !empty($job) && !empty($dur) && !empty($deg) && !empty($exp) && !empty($sal) && !empty($mark))
{
$dur = mysql_real_escape_string($dur);
$deg= mysql_real_escape_string($deg);
$exp = mysql_real_escape_string($exp);
$sal = mysql_real_escape_string($sal);
$mark = mysql_real_escape_string($mark);
$job = mysql_real_escape_string($job);
$query="INSERT INTO jobposting (duration,degree,experiance,salary,marks,Jobtitle) VALUES ('".$dur."','".$deg."','".$exp."','".$sal."','".$mark."','".$job."') ";
if ($query_run= mysql_query($query))
{
header('location : Main.html');
}
else
{
echo ' Data not Inserted! ';
}
}
With this it gives me server error or there was an error in CGI script.But when I write the variables in this form '$dur' instead of '".$dur." then the else conditon runs after insert query and displays data is not inserted.
However, i have written the same logic while inserting data in my another table and it inserts successfully.But there I put '$dur'.
I can't find the problem.Will be glad for your suggestions :)
I can't seem to find any other error by seeing this code expect for
$query="INSERT INTO jobposting (duration,degree,experiance,salary,marks,Jobtitle) VALUES ('$dur','$deg','$exp','$sal','$mark','$job') ";
//Use ".$job." only for stuff like '".md5($_POST['password'])."' otherwise this creates problem some times.
// Adding this always helps
if(!mysqli_query($con,$query))
{
die('error'.mysqli_error($con));
}
// in $con = $con=mysqli_connect("localhost","root","");
else
{
if ($query_run= mysql_query($query))
{
header('location : Main.html');
}
else
{
echo ' Data not Inserted! ';
}
}
I think by making these changes and making sure that your db name and other basic stuff are correct then you should be good to go otherwise, specify your exact error.
I'm currently struggling with a page that allows a user to complete one of two options. They can either update an existing item in the SQL database or they can delete it. When the customer deletes an option everything runs perfectly well, however whenever a customer updated an item it displays the Query failed statement from the delete function before applying the update.
It seems obvious to me that the problem must be in my IF statement and that the DeleteButton function isn't exiting if the $deleteno variable isn't set. Any help would be appreciated. Excuse the horribly messy code PHP isn't a language I am familiar with. (I have not included the connect information for privacy reasons)
function DeleteButton(){
#mysqli_select_db($con , $sql_db);
//Checks if connection is successful
if(!$con){
echo"<p>Database connection failure</p>";
} else {
if(isset($_POST["deleteID"])) {
$deleteno = $_POST["deleteID"];
}
if(!isset($deleteno)) {
$sql = "delete from orders where orderID = $deleteno;";
$result = #mysqli_query($con,$sql);
if((!$result)) {
echo "<p>Query failed please enter a valid ID </p>";
} else {
echo "<p>Order $deleteno succesfully deleted</p>";
unset($deleteno);
}
}
}
}
That is the code for the delete button and the following code is for the UpdateButton minus the connection information (which works fine).
if(isset($_POST["updateID"])) {
$updateno = $_POST["updateID"];
}
if(isset($_POST["updatestatus"])) {
if($_POST["updatestatus"] == "Fulfilled") {
$updatestatus = "Fulfilled";
} elseif ($_POST["updatestatus"] == "Paid") {
$updatestatus = "Paid";
}
}
if(isset($updateno) && isset($updatestatus)) {
$sql ="update orders set orderstatus='$updatestatus' where orderID=$updateno;";
$result = #mysqli_query($con,$sql);
if(!$result) {
echo "<p>Query failed please enter a valid ID</p>";
} else {
echo "<p>Order: $updateno succesfully updated!</p>";
}
}
Once again these are incomplete functions as I have omitted the connection sections.
if(!isset($deleteno)) {
$sql = "delete from orders where orderID = $deleteno;";
Are you sure you want to execute that block if $deleteno is NOT set?
P.S. You shouldn't rely on $_POST['deleteId'] being a number. Please read about SQL injections, how to avoid them and also about using prepared statements.
I've update your code, but you need to write cleaner code ( spaces, indents, etc ) this won't only help you to learn but to find your errors easily.
<?php
function DeleteButton()
{
#mysqli_select_db($con , $sql_db);
/*
Checks if connection is successful
*/
if(!$con){
echo"<p>Database connection failure</p>";
} else {
/*
Check if $_POST["deleteID"] exists, is not empty and it is numeric.
*/
if(isset($_POST["deleteID"]) && ! empty($_POST["deleteID"]) && ctype_digit(empty($_POST["deleteID"]))
$deleteno = $_POST["deleteID"];
$sql = "delete from orders where orderID='$deleteno'";
$result = #mysqli_query($con,$sql);
if(!$result){
echo "<p>Query failed please enter a valid ID </p>"
} else {
echo "<p>Order $deleteno succesfully deleted</p>";
unset($deleteno);
}
} else {
echo "<p>Please enter a valid ID </p>" ;
}
}
}
/*
Part 2:
===========================================================================
Check if $_POST["updateID"] exists, is not empty and it is numeric.
Check if $_POST["updatestatus"] exists, is not empty and equal to Paid or Fullfilled
*/
if( isset($_POST["updateID"]) &&
! empty($_POST["updateID"]) &&
ctype_digit(empty($_POST["updateID"]) &&
isset($_POST["updatestatus"]) &&
! empty($_POST["updatestatus"]) &&
( $_POST["updatestatus"] == "Fulfilled" || $_POST["updatestatus"] == "Paid" ) )
{
$updateno = $_POST["updateID"];
$updatestatus = $_POST["updatestatus"];
$sql ="update orders set orderstatus='$updatestatus' where orderID=$updateno;";
$result = #mysqli_query($con,$sql);
if(!$result){
echo "<p>Query failed please enter a valid ID</p>";
} else {
echo "<p>Order: $updateno succesfully updated!</p>";
}
}
There is an error in MySQL Syntax
$sql = "delete from orders where orderID = $deleteno;";
$deleteno after orderID must be inside single quotes.
change it to this $sql = "delete from orders where orderID = '$deleteno';";
I've been struggling to have a text form field required. So when some one doesn't fill his name he will receive an error like 'No title filled!'
I got this now but it doesn't work that well cause when I submit it insert into the db.
if(isset($_POST['submit'])) {
$update = "UPDATE post SET `title`='$_POST[title]', `pic`='$_POST[pic]', `youtube`='$_POST[youtube]' WHERE id = $_POST[id]";
$db->query($update) or die($db->error);
if($_POST['title'] == "") {
$error = "Title is required!";
}
if ($_POST['pic'] == "") {
$error = "Picture is required!";
}
if(isset($error)){
echo $error;
} else {
echo '<p>Your post has been updated!</p>';
}
}
You need to stop your code from being executed if an error is found, not just echo the error. All your other code that submits the data to the database should ONLY be executed if there is no error. Try something like this:
Edit: Upon seeing the update to your code, this is what you need to do:
if(isset($_POST['submit'])) {
if(!isset($_POST['title']) || trim($_POST['title']) == "") {
$error = "Title is required!";
}
if (!isset($_POST['pic']) || trim($_POST['pic']) == "") {
$error = "Picture is required!";
}
if(isset($error)){
echo $error;
} else {
$update = "UPDATE post SET `title`='" . mysql_real_escape_string($_POST['title']) . "', `pic`='" . mysql_real_escape_string($_POST['pic']) ."', `youtube`='" . mysql_real_escape_string($_POST['youtube']) ."' WHERE id = " . mysql_real_escape_string($_POST['id']);
$db->query($update) or die($db->error);
echo '<p>Your post has been updated!</p>';
}
}
The problem is, your data was being submitted to the database no matter what happened after with the validation - by the time you checked for errors it was too late, as the SQL had already been executed.
If you do it the way shown above, it will only submit if the $error variable is not set, which is what you want.
I wouldn't just rely on
if($_POST['title'] == "")
because it will not work if someone enters a space into the text field. For one thing, a title shouldn't be too long? So you can set a max-length for it?
Also maybe run a few more checks such as:
I wouldn't just rely on
if(!isset($_POST['title'] || $_POST['title'] == "" || $_POST['title'] == " ")
{
// Error
}
else
{
// Database query
}
You want the else, otherwise it will always execute the database query, whether or not they haven't filled out the form properly.
My header is not working.
<?php
$name = mysql_prep($_POST['name']);
$pastor = mysql_prep($_POST['pastor']);
$head = mysql_prep($_POST['head']);
$schedule = mysql_prep($_POST['schedule']);
$venue = mysql_prep($_POST['venue']);
$id = mysql_prep($_GET['ministryid']);
$errors = array();
$required_field = array('name', 'pastor', 'address', 'schedule', 'venue');
foreach ($required_field as $fieldname) {
if(!isset($_POST[$fieldname]) || empty($_POST[$fieldname])) {
$errors[] = $fieldname;
echo "Sorry, you missed to complete {$fieldname} <br />";
}
else {
$query = "UPDATE ministry SET
name = '{$name}',
pastor = '{$pastor}',
head = '{$head}',
schedule = '{$schedule}',
venue = '{$venue}'
WHERE id = {$id}";
mysql_query($query);
if(mysql_affected_rows() == 1) {
header('location: editministry.php?');
exit;
} else {
echo "Updating Failed on {$s_ministry['name']} <b />".mysql_error();
exit;
}
}
}
require_once("include/footer.php");
Every time I have successful update, the link change its address.
For example, when I'm updating id = 3, the address will change to editministry.php?ministryid=3.
You dont send anything along your URL, thats why your header won't work. Check for yourself.
if(mysql_affected_rows() == 1) {
header('location: editministry.php?');
exit;
Your link will become effectivly baseUrl/editministry.php?.It searches than for a variable, which is not defined. I am not sure how you actually can pass on a variable that you didnt define in a link, yet it sends you there. Don't know. But if you just tell it to the hard link without the questionmark, it should go to that page. For me it works at least within my code. For you it would be:
if(mysql_affected_rows() == 1) {
header('location: editministry.php' );
exit;
In my code it looks like this:
header( "Location: http://" . strip_tags( $_SERVER ['HTTP_HOST'] ) . "/newHolo/index.php" );
<?php
if (intval($_GET['page']) == 0) {
redirect_to("staff.php");
}
$id = mysqli_prep($_GET['page']);
$query3 = "DELETE FROM page WHERE id = {$id}, LIMIT 1";
$result = mysqli_query($connection, $query3);
if (mysqli_affected_rows($connection) == 1) {
redirect_to("staff.php");
} else {
// Deletion Failed
echo $id ."<br />" . $query3 . "<br />" . $result . "<p>Subject
deletion failed.</p>";
echo "<p>" . mysqli_error() . "</p>";
echo "Return to Main Page";
}
// Keep on working Edit:2#
mysqli_query($connection, "DELETE FROM pages WHERE id = 11 ");
//- Works
Edit 3#
$id = $_GET['page'];
echo "<p>" . $id ."</p>";
$query3 ="DELETE FROM pages WHERE id = {$id} ";
mysqli_query($connection,$query3 );
// Still Works -- YaY for working backwards
// Edit #4 By "now it might be obvious what my error was "pages" not "page"
// Thanks everyone - And thank you for telling me about the error page
// My defense - newbie- Anyway Lesson from this - working backwards
// Takes a while, Error checking Fast!!!!!!
?>
$connection is started and selected. The $id is selected successfully, and the $page = $id, but it still will not work. $query 3 seems fine, but Deletion failed. I don't have any idea what the error is. Thanks for any help in advance.
-Josh Edit Check Error Check
You have a comma after the ID:
$query3 = "DELETE FROM page WHERE id = {$id}, LIMIT 1";
^ remove this
I don't have any idea what the error is.
That's because you didn't check. Every time you prepare or execute a query, you need to check for errors. Most of the functions in mysqli return FALSE if they encounter an error.
$result = mysqli_query($connection, $query3);
if ($result === false) {
trigger_error(mysqli_error($connection), E_USER_ERROR);
header("Location: /error.php");
exit;
}
The failure to check for error cases is one of the most common blunders committed by database programmers.
if ($page == get_page_by_id($id)) {
== for comparison
=== to compare the value and the cast
$val = true;
if ($val === true) {
echo "\$val is bool(true)";
}
if ($val == "true") {
echo "\$val matches value";
}
if ($val === "true") {
// this will never happen
} else {
echo "\$val doesnt === \"true\"";
}
try to use php_flag display_errors on in your .htaccess
this will allow you to see and identify php errors.