mySQL insert HTML form posting problem on results... Need help - mysql

I am stumped!! I can't figure this out.
I created an HTML form that inserts a record into mySQL. It works and I can see the new records I add/insert. BUT, I get the wrong confirmation page: I get a the FAIL PAGE instead of the SUCCESS page. I see the new record but I always get taken to the fail page. Why?
Is there something wrong with the script or a setting inside mySQL?
Here is my form post script:
<?
$host="XXXXXXXXXXXX";
$username="XXXXXXXX";
$password="XXXXXXXX";
$db_name="XXXXXXXXX";
$tbl_name="cartons_current";
mysql_connect("$host", "$username", "$password") or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$order = "INSERT INTO cartons_current (type, part_no, description, count,
size, min, max, qty)
VALUES
('$_POST[type]', '$_POST[part_no]', '$_POST[description]', '$_POST[count]',
'$_POST[size]', '$_POST[min]', '$_POST[max]', '$_POST[qty]')";
$result = mysql_query($order);
$result = mysql_query($order); //order executes
if ($result) {
$part_no = $_REQUEST['part_no'] ;
header("location: inv_fc_result_new_success.php?part_no=" . urlencode($part_no));
}
else {
header("location: inv_fc_result_new_fail.php");
}
?>

Your code looks OK, except for the possibility that mysql_query() gets called twice. If that is actual code, then I suspect the first call loads the record you are seeing, and the subsequent call returns the error message.
$result = mysql_query($order);
$result = mysql_query($order); //order executes

You appear to be calling mysql_query twice. If it's not a typo in copying the code onto stackoverflow then this could be the issue.
The first call is returning true but second call is returning 'false' hence the fail page is displayed

Related

Code Igniter - not showing the entry I need

I have the following code to get one line for each MAC with the LATEST state. The problem I have is that I get one line but not with the latest state but rather with the earliest.
function get_active_devices($min_duration, $max_duration)
{
//get all active devices DESC order
$this->db->distinct();
$this->db->group_by('mac');
$this->db->order_by("id", "desc");
$this->db->select('data.mac, state, time, iot_bo.notified, iot_bo.op_state, iot_bo.Name');
$this->db->where('time >', time()-$max_duration);
$this->db->where('time <', time()-$min_duration);
$this->db->join('iot_bo', 'iot_bo.mac = data.mac');
$this->db->where('iot_bo.op_state', '1');
$query = $this->db->get();
return $query;
}
Have you tried the query without the distinct and groupBy first? May be the result you want isn't in the total result set to begin with. Because there doesn't seem to be anything wrong with your use of db methods as it is.

MySQL Query not updating database

Perhaps I am just being a complete idiot but I am trying to insert a record into a MySQL table but it doesn't seem to be working. When I test it (i.e. get the script to echo the values so I can check that they are being posted by the form), they are being sent but the query isn't posting to the database. Like I said, perhaps I am being a complete idiot but I felt that perhaps a fresh set of eyes might speed up my troubleshooting because I have been fighting with this issue for the past 2 hours!
Here is the code:
// Connects to your Database
mysql_connect("localhost", "dbuser", "dbpword") or die(mysql_error());
mysql_select_db("dbname") or die(mysql_error());
// Get Variables
$sectorid = $_POST['sectorid'];
$parentid = $_POST['parentid'];
$sectorname = $_POST['sectorname'];
$status = $_POST['status'];
$creon = $_POST['creon'];
$creby = $_POST['creby'];
$modon = $_POST['modon'];
$modby = $_POST['modby'];
//Insert Record
mysql_query("INSERT INTO cand_emp_sector (sectorid, parentid, sectorname, status, creon, creby, modon, modby)
VALUES ('$sectorid', '$parentid', '$sectorname', '$status', '$creon', '$creby', '$modon', '$modby)");
//On completion, redirect to next page
header("Location: canddb.new.7i.php");
Any assistance would be greatly appreciated.
Thanks
you are missing a quote at the end
, '$modby')");
^---------here
Check the result for errors:
$result = mysql_query("INSERT INTO cand_emp_sector (sectorid, parentid, sectorname, status, creon, creby, modon, modby)
VALUES ('$sectorid', '$parentid', '$sectorname', '$status', '$creon', '$creby', '$modon', '$modby)");
if($result === false) die('query failed..');

mysql_affected_rows sometimes returns 0 instead of 1

I have a strange problem with php scripts - mysql_affected_rows() sometimes returns "0" for no reason.
There is a similar question #stackoverflow and answer to this question is:
MySQL only actually updates a row if there would be a noticeable difference before and after the updat.
But this is not my case. For example, if value before update is 1320402744 and value after update is 1320402944 mysql_affected_rows() anyway return "0". Is this difference not enough noticable?
Below are 3 files. As you can see, all files include file "functions.inc.php" which calls function "online()".
File "login.php" is working fine. It inserts a new row in "session" table correctly.
File "content.php" is working fine - it displays content and correctly runs function "online() in "functions.inc.php".
Then I call file "test.php". It deletes "something from sometable" correctly. Then it refreshes itself (Header("Location: /test.php");). After refreshing I am logged off.
I added this to "online()" function:
echo "affected_rows";
It returns 0.
I added more code to "online() function:
$checkuser = mysql_query("SELECT userid FROM session WHERE userid = '" . $_SESSION['id'] . "'") or die('Error');
$found = mysql_num_rows($checkuser);
echo $found;
$result = mysql_query("UPDATE session SET time='$ctime' WHERE userid='".$_SESSION['id']."'") or die('Error');
$affected_rows = mysql_affected_rows();
if ($affected_rows != 1) #session_destroy();
echo $affected_rows;
The result is 1 and 0.
I checked the database. "time" field in session table has been updated.
So, I can't understand how is it possible that the row exists, it updates correctly but mysql_affected_rows(); returns 0, and why this happends only if te same page has been refreshed.
functions.inc.php
<?php
#ob_start();#session_start();
#mysql_connect(C_HOST, C_USER, C_PASS) or die('Cant connect');
#mysql_select_db(C_BASE) or die('Cant select DB');
function online() {
$ctime = time()+1800;
if((isset($_SESSION['id']))&&(is_numeric($_SESSION['id']))) {
$query = mysql_query("UPDATE session SET time='$ctime2' WHERE userid='".$_SESSION['id']."'") or die('Error');
$affected_rows = mysql_affected_rows();
if ($affected_rows != 1) #session_destroy();
}
}
//many other functions go here
online();
?>
login.php
<?php
include_once 'configuration.inc.php';
include_once 'functions.inc.php';
//many things go here
$upd = mysql_query("INSERT INTO session VALUES ('" . $i['id'] . "','$ctime')") or die('Error2');
Header("Location: /content.php?justlogged=1");
die;
?>
content.php
<?php
include_once 'configuration.inc.php';
include_once 'functions.inc.php';
//many thing go here
echo "content";
?>
test.php
<?php
include_once 'configuration.inc.php';
include_once 'functions.inc.php';
if (isset($_GET['tid'])&&(is_numeric($_GET['tid']))){
$result = mysql_query("delete from some_table where something = '" . $_GET['tid'] . "'") or die('Error123a');
Header("Location: /test.php");
die;
}
//file content
?>
In your function.inc.php you call online() - session time is changed every second. But can it be that you're switching between pages (login, content, test) more faster than 1 second? In that case time would be the same and you'd get session destroy because of unaffected rows
Edit:
Yes. As I thought.
See how it comes:
you call login.php: after successful login it creates new session with time X. After this you're immediately redirected to content.php (time is still X) which calls online again. And of course, as you redirected immediately - time is the same.. so already at point of content.php session is already destroyed, because time wasn't changed.

$SQL UPDATE doesn't work when added WHERE CLAUSE

I know I am simply missing the simplest thing here but cant seem to figure it out.
so this works with this code but changes all rows of the database as opposed to just the one with the page id...
<? $pageid= $_GET["id"];
$sql = "SELECT id, first_name, last_name, email, bio, job, job2, job3 FROM `".weapons."` WHERE id = $pageid";
if(isset($_POST['Update']))
{
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$job = $_POST['job'];
$job2 = $_POST['job2'];
$job3 = $_POST['job3'];
$bio = $_POST['bio'];
$email = $_POST['email'];
$sql = "UPDATE weapons SET first_name='$first_name', email='$email' , job='$job', job2='$job2', job3='$job3', bio='$bio', last_name='$last_name'";
if (#mysql_query($sql)) {
echo('<p>Update Complete</p>');
} else {
echo('<p>Error updating: ' . mysql_error() . '</p>');
}
}else{ ...
however when adding the WHERE clause, like as follows
$sql = "UPDATE weapons SET first_name='$first_name', email='$email' , job='$job', job2='$job2', job3='$job3', bio='$bio', last_name='$last_name' WHERE id = $pageid";
I get an error
Error updating: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
Any help would be great, thanks
EDIT
I actually missed a super easy thing, which is what I initially assumed, I had at first in my form had <form method='post' enctype='multipart/form-data' action='submit.php'> however that obviously messed up the get id because there isnt an idea, so even if that page was submit.php?id=4 when you hit submit it wouldnt run because the id would be gone.
Switching the code to <form method='post' enctype='multipart/form-data' action='#'> did just the trick.
Thanks for the help guys and I am looking into the sql injection now and working on how to better secure my site.
Please escape your strings before you create your SQL statement. Various characters in your input values will both break your query and open a HUGE security hole. That may very well be your problem. Look at this post for more info How can I prevent SQL injection in PHP?
In short, you assignments would look like this:
$first_name = mysql_real_escape_string($_POST['first_name']);
echo $sql; before you run it and post what that outputs.

mysql_affected_rows() always returns 1 even though no row was updated

What I am trying to do is: (programmatically)
Update status where id is something, if no rows where updated, give error: we cannot find the record with id something, otherwise give message success.
Here I am using mysql_affected_rows() to know if a row was updated or not, but it always return 1, so the user gets a success message, even though there was no row updated.
Can anyone tell me what could it be?
Here's the code:
function update_sql($sql) {
$this->last_query = $sql;
$r = mysql_query($sql);
if (!$r) {
$this->last_error = mysql_error();
return false;
}
$rows = mysql_affected_rows();
if ($rows == 0) return true; // no rows were updated
else return $rows; }
This code returns 1.
That is because true will print out as "1" if you use echo. For debugging try using var_dump(), or let your function return 0 (which seems to me, in this case, the better option).
One little note; I think you should try to make your code a bit more readable (if the code in your question has the same layout as the code in your file). Try to indent code blocks, use separate lines for closing curly brackets, etc...
This is just a guess...
Maybe your function works as excepted? Maybe this piece of code if ($rows == 0) return true; works fine, and returns true but you treat that value as integer (boolean true can be displayed as 1)? Do: var_dump(uddated_sql('YOUR QUERY')) and check whether it returns boolean true or integer 1 value.