mysql_insert_id function is returning 0 - php

I have been trying to figure out why this function is working on chrome, but not on firefox.
I have an auto increment field that is my primary key that I get my id from. Here is my code.
if (isset($_GET['id'])) {
$id = $_GET['id'];
} else {
$id = mysql_insert_id();
echo $id;
}
I've tried putting my connection in the function as follows, but it still does not work. Any pointers would be appreciated. Also, I know of mysqli functions, I am using these functions because the user's setup is quite old.
$id = mysql_insert_id($conn);
Here is my code that is doing the insert.
sprintf("INSERT INTO `trade_show_orders` (`SetupDate`,`SetupEndDate`,`ShowName`,`Location`,`Literature`,`StartDate`,`EndDate`,`Attendees`,`Projected`,`File`,`Giveaways`,`AddressBox`,`LocationType`,`Title`,`FirstName`,`LastName`,`Email`,`AddressOne`,`AddressTwo`,`Zip`,`Special`,`OrderDate`,`ShippingLocation`,`ShippingAddressOne`,`ShippingAddressTwo`,`ShippingZip`,`ShippingSpecial`) VALUES ('$setupDate','$endSetup','%s','%s','$values','$eventStart','$eventEnd','%d','%d','".basename($_FILES['fileUpload']['name'])."', '%s','off','%s','%s','%s','%s','%s','%s','%s','%d','%s',NOW(),'%s','%s','%s','%d','%s')", mysql_real_escape_string($_POST['showName']), mysql_real_escape_string($_POST['location']), $_POST['numberAttendees'], $_POST['visitors'], mysql_real_escape_string($_POST['giveaways']), mysql_real_escape_string($_POST['locationType']), mysql_real_escape_string($_POST['personalTitle']), mysql_real_escape_string($_POST['personalFirstName']), mysql_real_escape_string($_POST['personalLastName']), mysql_real_escape_string($_POST['personalEmail']), mysql_real_escape_string($_POST['personalAddressOne']), mysql_real_escape_string($_POST['personalAddressTwo']), $_POST['personalZip'], mysql_real_escape_string($_POST['personalSpecial']), mysql_real_escape_string($_POST['shippingLocation']), mysql_real_escape_string($_POST['shippingAddressOne']), mysql_real_escape_string($_POST['shippingAddressTwo']), $_POST['shippingZip'], mysql_real_escape_string($_POST['shippingSpecial']));

mysql_insert_id() will only return an ID if you've done an INSERT query WITH THE CURRENT CONNECTION. That means it will not return an ID from a page request "three clicks" ago. it will not return an ID done by some other script that's executing at the same, because that's done using a different connection to mysql.
So show the rest of the code that actually does the insert. PHP shouldn't care at all what browser's running on the remote it. It's just an HTTP request with some data as far as PHP is concerned. If there is a browser-specific issue, it'll be in some client-side code that's blowing up, e.g. some bad javascript doing an AJAX request and not filling out a field properly.

Turns out it had nothing to do with my insert.
Apparently, when you use images with submits on a form in Firefox, IE. It renames the image submit from "submit" to "submit_x" or "submit_y"
Chrome and Safari look for both submit and submit_x,submit_y with images.
Firefox and IE 7,8,9 only look for submit_x and submit_y, which explains the reason why it was only working on chrome.

Related

php GET requests and their subsequent use as a variable (in an SQL confdition)

I have successfully extracted the correct data from my database during testing (its just a prototype - so yes I know its not secure SQL). The test SQL is
$sql=
SELECT *
FROM jobcards
WHERE jobnumber='$jobnumber'
";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0)
{loop}
The issue is the source of the data to which $jobnumber is set.
If during testing I set $jobnumber to the string Agen912-491 (implicitly) I get out of the database exactly what I should get out. However here is the problem.
I am clicking from a link on another page. The link creates the URL:-
domain.php/jobcard.php?jobnumber=%20Agen912-491
which take me to the page on which the SQL query (and the output) resides. So on the page I set
$jobnumber = $_GET["jobnumber"];
echo $jobnumber;//testing
to request (and test) the jobnumber (passed from the link) that I need to insert into the WHERE condition. As expected the echo correctly returns Agen912-491. So exactly the same string (it seems) as the implicit value used succesfully in testing. All good so far.
However when I then set $jobnumber= $_GET["jobnumber"]; the database query fails to find any records. [In desperation I fudged the process so that the variable $jobnumber = $_SESSION ["jobnumber"]; (and ensured via an echo that $_session[] gave me Agent912-491). Now the database correctly returns the record again!
So for some reason the $GET["jobnumber"]; statement when set to $jobnumber is failing [even though when it is echoed it returns the correct value that works implicity (and when set it via $s[session]. So there is clearly an issue with a) requesting $_GET["jobnumber"]; b) setting it to the $jobnumber and then c) using that in the WHERE statement. Everything else works as does setting $jobnumber implicitly or via $_session.
I have an incline it might be something to do with santitising the $_GET result before using it. But that really is a guess and even if correct I dont know what exactly to try out.
Help would be really appreciated. Many thanks.

This add new member code worked fine until I switched webhosts for my site now it does not and I have no idea why

I am having an issue with my adding a new member page,, also having an issue with my login page which is similar in code. Both worked fine, tested multiple times and ways and then I switched hosting companies. The rest of the database driven site works fine still except this part. Have no idea why and possibly just need fresh eyes on it. I am fairly new to php and mysql to begin with,,, then attempting to learn the newer versions to keep my code upgraded has me at this point unable to figure out why the code is no longer working. Any help would be much appreciated. Thanks.
The page will run up to this point,, I have confirmed that using echo, then it fails. The page itself, does not load, justs stays completely blank and the little loading wheel in the tab corner just spins and spins.
$sql="SELECT * FROM table WHERE field LIKE'$username'";
$rs=$db->query($sql);
$arr = $rs->fetch_all(MYSQLI_ASSOC);
// test to make sure there was not an issue loading the db
if($rs != true) { // start second if in nested section
// if any errors in reading the db redirect to a general db is down error page
//close db connection
mysqli_close($db);
// redirect header goes here, removed for this post
} else { // else to go with second if
// get number of rows returned in this case should be 0 or 1
$rows_returned = $rs->num_rows;
echo "num of rows are $rows_returned";
} // end second if

SQL Insert won't insert on all fields

I have PHP generating an HTML form and I'm trying to write a script that will update the information in the database. For some reason it works on some of the fields and not others.
Code which won't work:
PHP-Form that users can change details within
echo"<form name='details'>";
echo"<p>Surname: <input type='text'id='surname' value='".$row['Surname']."'/></p>;
<p>Telephone: <input type='text'id='phone' value='".$row['Telephone']."'/></p>;
<p>Postcode: <input type='text' id='postcode' value='".$row['Postcode']."'/></p>;
<p>House/Flat Number: <input type='text' id='number' value='".$row['Number']."'/></p>";
AJAX - sends changes to server via querystring
var sname = document.getElementById('surname').value;
var tel = document.getElementById('phone').value;
var num = document.getElementById('number').value;
var pcode = document.getElementById('postcode').value;
var queryString = "?username=" + username +"&email="+email....";
ajaxRequest.open("GET", "url" + queryString, true);
ajaxRequest.send(null);
PHP - execute update command
//connect to server
...
//get variables
$sname = $_GET['sname'];
$pcode = $_GET['pcode'];
$tel = $_GET['tel'];
$num=$_GET['num'];
//process update
$update ="UPDATE User SET Surname='$sname',Telephone='$tel',Number='$num',
Postcode='$pcode' WHERE Username='$username'";
//if query, display success
if(mysqli_query($update))
{
echo"success";
}
else
{
echo"error";
}
//else display error
The query executes fine, but the values aren't displaying within the database. My other variables (username, password etc) all update fine. All database fields are type VARCHAR(80).
EDIT: I do have the query being executed. This still results in the surname, postcode, number and telephone field not being updated.
Ignoring for the moment all the other issues with this code and approach (SQL injection issues, GET vs. POST issue, etc.), and dealing with the update not changing things as expected, there are a couple of things to check.
Try outputing the update query in your logs and make sure that it actually looks like what your expecting. It could be that the values you're meaning to push across the wire are not making it into the query or that.
Verify that running the query by hand in an standalone SQL client (mysql, squirrel, etc...) Actually updates a record. It's entirely possible that a valid update query may not match any records. (Say the username value you're looking for does not match one that's in the database.
Not knowing your infrastructure, I'd suggest some sanity checks: Are you actually pointing at the right database? Do you have a your update wrapped in a transaction that's rolling back? etc ...
A few other tips:
I would suggest looking at PDO, in particular how Prepared Statements work. The kind of query you're building above is someone to run off with all your data or worse. While not a panacea, prepared statements are a solid first step.
Take a look at Jquery's Ajax functions. In particular the post method. It provides a simple interface for making ajax calls without having to construct special url strings. Plus, switching to a POST will avoid your data showing up in webserver logs files.

Correct way to use an if statement and a $GET in PHP

Am fairly new to PHP and am making a basic CRUD style management system. I Have an update page and it displays data from a News table, and populates a form with it. The current picture ?(reference) is pulled through and displayed on the form. However if a user wants to change the picture they can press a 'delete' button and then I have written some PHP to display a upload button, set the values in the database for the image to null and hide the delete button, allowing the user to upload a new picture.
The Delete button only removes the reference (path) to the picture from the database, it doesn't delete the actual picture.
This is the HTML control to show the image and delete button. It also shows how the delete button works:
<td align="right">Image 1:</td>
<td align="left"><img src="uploads/newsimages/<?php echo $row["Image"]; ?>" width="230" border="0"> delete</td>
As you can see, when clicked it sets change=imagex and cid= the current news id.
There is then an if statement I have written, but it doesn't seem to only get activated when the delete button is clicked. Because I always get an error that 'cid' is undefined. It is as follows:
<?php
if (isset($_GET['change'] = "image1") {
$query = "UPDATE Table_Name SET Image = '' WHERE NewsID =".$_GET['cid']." ";
}
?>
I am pretty sure my lack of PHP knowledge is letting me down and I am trying to go about this the wrong way, because however I alter the if statement it always gives me an error. First it was cid is undefined so I changed to id but i already use that for something else, another query/function. I hope that all amde sense, can anyone tell me where Im going wrong?
You are missing a parenthesis + you have to specify individually:
if (isset($_GET['change'] = "image1") {
Change to:
if (isset($_GET['change']) && $_GET['change'] == "image1") {
Some more things to consider:
1) Don't use unsanitized values directly from $_GET in a mysql query
WHERE NewsID =".$_GET['cid']."
It is very easy to exploit this with some funky sql injection (see http://xkcd.com/327/ ).
If you are using numeric values for cid, you should cast your $_GET value to integer to prevent sql injection:
$cid = (int)$_GET['cid];
$query = '(...)WHERE NewsID = '.$cid.' limit 1';
Or even better:
$cid = (int)(array_key_exists('cid', $_GET) ? $_GET['cid'] : 0);
if ($cid) {
$query = (...)
}
If you need this kind of sanitizing in different places, you should think about writing a helper function for it to keep your code readable.
2) Don't use GET requests to change data on your server
Imagine a google bot browsing your site and following all those links that you use to delete images. Other scenarios involve users with prefetch plugins for their browsers (e.g. Fasterfox). Also, GET requests may be cached by proxies and browsers, so that the request won't hit the server if you click the link.
The HTTP specification comes with numerous request methods, the most important ones are:
GET to fetch content from the server
PUT to store new information on the server
POST to update existing information on the server
To update your news record (by removing the image) the appropriate method would be POST. To send a POST request, you can use the <form method="POST"> tag.
try this
<?php
if (isset($_GET['change']) && $_GET['change'] == "image1") {
$query = "UPDATE Table_Name SET Image = '' WHERE NewsID =".$_GET['cid']." ";
}
?>

inserting php session id into database from php://input callback

i have a callback page, that i am using to insert data in a db. when i load this page. and echo $_SESSION['user_id']. it echos the user_id, and inserts it into the db. however when i am trying to insert the data while doing the callback function, the $_SESSSION['user_id'] is ignored and the other data is succesfully inserted. why is this?
echo $_SESSION['user_id'];
$decodedJSON = json_decode(file_get_contents('php://input'), true);
$account = $decodedJSON['account'];
$query_insert = "insert into video (account,userid) values ($account,$_SESSION['user_id'])";
$result_insert = mysql_query($query_insert);
When i refresh the page, $_SESSION['user_id'] is inserted. But when i try to run the callback function, $account is inserted, but $_SESSION['user_id'] is not.
I'm not 100% sure of how this all fits together with your code sample, but if you're trying to pass somethign to stanard input and then run the PHP, you also need to pass the sessionID.
When you call the code from your borwser, cookies magically handle all that for you, and the sessions ID is passed in a cookie. But if you're calling from another source, cookies are not passed.
I could explain how to do it, but nothing better than the PHP manual: http://php.net/manual/en/session.idpassing.php - basically append the SID to the end of hte URL.
But note the comment about "session.use_trans_sid" which is disabled by default and needs to be enabled in php.ini

Categories