mysqli stores php variable not value - php

This is driving me nuts. I am using the jQuery image upload and crop from
http://www.webmotionuk.co.uk/php-jquery-image-upload-and-crop/
I am using a modified version of the suggestion on here to store the file location in a MySQL database. The mod is that I use INSERT on a table it works great except one thing, the 'owner' variable $id is being stored as $id and not as the value of $id. I can echo the value if $id on each $_POST so I know it's there.
I am pretty sure my syntax is correct but I don't understand why it is doing this.
$cropped = resizeThumbnailImage($thumb_image_location, $large_image_location,$w,$h,$x1,$y1,$scale);
//connect to the database
include 'config.php';
// check connection
if (mysqli_connect_errno()) {
exit('Connect failed: '. mysqli_connect_error());
}
$sql = "INSERT INTO `photos` (`id`,`owner`,`url`) VALUES ('id','".$id."','".$thumb_image_location."')";
// Performs the $sql query on the server to insert the values
if ($conn->query($sql) === TRUE) {
$conn->close();}
//Reload the page again to view the thumbnail
header("location:".$_SERVER["PHP_SELF"]);
exit();
The first line is 246 and the last 3 are the orginal 247-250.
Thanks for any help you can provide.
Ok, I don't know if this is my brain fart or an issue with PHP or a bit of both. I have $id assigned from the _SESSION variable in the header of each page AND (having forgotten that) I was passing $id as _POST data (same value). Once I cut out the _POST data passing and just pulled the _SESSION variable it works fine. But assigning a variable multiple times shouldn't be an issue, should it?

the query line needs to be like this:
$sql = "INSERT INTO `photos` (`id`,`owner`,`url`) VALUES ('id','$id','$thumb_image_location')";
your syntax works fine too, as seen here
this is how my syntax works, here
Note: both work the same, so still trying to figure out what's wrong in OP's code.

Related

MySQL Insert Into PHP Not Working

I am currently looking to run a basic insert query using PHP to submit HTML form data to MySQL database.
Unfortunately however the insert process isnt running.
In my Insert syntax I have tried including $_POST[fieldname], ive tried including variables as below, and ive even played around with different apostrphes but nothing seems to be working.
as a side dish, im also getting truck load of wamp deprication errors which is overwhelming, ive disabled in php.ini and php for apache.ini file and still coming up.
If anyone can advise what is wrong with my insert and anything else id be much thankful.
Ill keep this intro straightfoward.
Person logs in, if they try to get in without login they go back to login page to login.
I connect to database using external config file to save me updating in 50 places when hosting elsewhere.
Config file is working fine so not shown below.
database is called mydb.
Im storing the text field items into variables, then using the variables in the insert query.
unitID is an auto increment field so I leave that blank when running the insert.
Unfortunately nothing is going in to the mysql database.
Thanks in advance.
PS the text fieldnames are all correctly matched up
<?php
//Start the session
session_start();
//check the user is logged in
if (!(isset($_SESSION['Username']) )) {
header ("Location: LoginPage.php?i=1");
exit();
}
//Connect to the database
include 'config.php';
$UserName = $_SESSION['Username'];
$UserIdentification = $_SESSION['UserID'];
if(isset($_GET['i'])){
if($_GET['i'] == '1'){
$tblName="sightings";
//Form Values into store
$loco =$_POST['txtloco'];
$where =$_POST['txtwhere'];
$when =$_POST['txtdate'];
$time =$_POST['txttime'];
$origin =$_POST['txtorigin'];
$dest =$_POST['txtdest'];
$headcode =$_POST['txtheadcode'];
$sql= "INSERT INTO sightings (unitID, Class, Sighted, Date, Time, Origin, Destination, Headcode, UserID) VALUES ('','$loco', '$where', '$when', '$time', '$origin', '$dest', '$headcode', '$UserIdentification')";
mysql_select_db('mydb');
$result=mysql_query($sql, $db);
if($result){
$allocationsuccess = "Save Successful";
header ('Refresh: 2; url= create.php');
}
else {
$allocationsuccess = "The submission failed :(";
}
}
}
?>
"unitID is an auto increment field so I leave that blank when running
the insert"
That's not how it works. You have to omit it completely from the INSERT statement. The code thinks you're trying to set that field to a blank string, which is not allowed.
$sql= "INSERT INTO sightings (Class, Sighted, Date, Time, Origin, Destination, Headcode, UserID) VALUES ('$loco', '$where', '$when', '$time', '$origin', '$dest', '$headcode', '$UserIdentification')";
should fix that particular issue. MySQL will generate a value automatically for the field and insert it for you when it creates the row.
If your code had been logging the message produced by mysql_error() whenever mysql_query() returns false then you'd have seen an error being generated by your query, which might have given you a clue as to what was happening.
P.S. As mentioned in the comments, you need to re-write your code with a newer mysql code library and better techniques including parameterisation, to avoid the various vulnerabilities you're currently exposed to.

MySQL entry storing with blank value in PHP

Have the following code that's executed when a script is ran. (I've just changed the login for display purposes).
<?php
$conn = mysql_connect("localhost", "root", "pw123");
mysql_select_db("test_db", $conn);
$sql = "INSERT INTO test_table (fname)
VALUES ('$fname')";
mysql_query($sql);
mysql_close($conn);
?>
I've edited the code down slightly so it doesn't show every value I'm trying to enter, but essentially, everything is entering as a blank value, or in the case of numerical inputs is defaulting to 0. I can't seem to figure out why this is. The variables are definitely not blank before hand as I've got them out putting on the web page to test as such.
For reference I assign $fname a value when the input box is changed using :
fname = $("#fname").val();
(Posted on behalf of OP):
Solved this myself anyway, instead of executing the MySQL statements in the initial page that user enters data, I moved it to the secondary web page, which opens once a user has submitted their information.
$fname is empty in your script and you need declarate the variable before:
$fname = 'David';
$sql = "INSERT INTO test_table (fname) VALUES ('$fname')";
:)

PHP - Reducing an independent record stock value by 1

I'm currently doing a school project and I'm using dreamweaver along with a backend database using phpMyAdmin.
Now, what i need to do is, when I click the button, it will reduce the stock column value in the "products" table by 1.
However there are different products in the table. Shown below:
http://i.stack.imgur.com/vLZXQ.png
So lets say, A user is on the game page for "Destiny" and clicks on the Buy now button, how can i make it reduce the stock level by one, but only for the Destiny record and not for the Fifa 15 column. So Destiny stock becomes 49, but Fifa stays 50. Will i just need to make each button have a different script or?
Currently, I made a button in the page, which links to an action script, but im not sure what sort of code i will be using.
Thank you
xNeyte is giving you some good advice, but it comes across to me that you - Xrin - are completely new to programming database contents with PHP or similar?
So some step by steps:
MYSQL databases should be connected with one of two types of connection - PDO and MySQLi_ . MySQL databases will also always work using the native MySQL but as xNeyte already mentioned - this is deprecated and highly discouraged .
So what you have is you pass your information to the PHP page, so your list of games is on index.php and your working page that will update the number of games ordered would be update.php, in this example.
The Index.php file passes via anchor link and $_GET values (although I highly recommend using a php FORM and $_POST as a better alternative), to the update.php page, which needs to do the following things (in roughly this order) to work:
Update.php
Load a valid database login connection so that the page can communicate with the database
Take the values passed from the original page and check that they are valid.
establish a connection with the database and adjust the values as required.
establish the update above worked and then give the user some feedback
So, step by step we'll go through these parts:
I am going to be a pain and use MySQLi rather than PDO - xNeyte used PDO syntax in his answer to you and that is fully correct and various better than MySQLi, for the sake of clarity and your knowledge of MySQL native, it may be easier to see/understand what's going on with MySQLi.
Part 1:
Connection to the database.
This should be done with Object Orientated - Classes,
class database {
private $dbUser = "";
private $dbPass = ""; //populate these with your values
private $dbName = "";
public $dbLink;
public function __construct() {
$this->dbLink = new mysqli("localhost", $this->dbUser, $this->dbPass, $this->dbName);
}
if (mysqli_connect_errno()) {
exit('Connect failed: '. mysqli_connect_error());
}
if ( ! $this->dbLink )
{
die("Connection Error (" . mysqli_connect_errno() . ") "
. mysqli_connect_error());
mysqli_close($this->dbLink);
}
else
{
$this->dbLink->set_charset("UTF-8");
}
return true;
} //end __construct
} //end class
The whole of the above code block should be in the database.php referenced by xNeyte - this is the class that you call to interact with the database.
So using the above code in the database.php object, you need to call the database object at the top of your code, and then you need to generate an instance of your class:
include "database.php"; ////include file
$dataBase = new database(); ///create new instance of class.
Now When you write $dataBase->dbLink this is a connection to the database. If you do not know your database connection use the details PHPMyAdmin uses, it carries out its tasks in exactly the same way.
Sooo
Part 2:
That is that your database connection is established - now you need to run the update: First off you need to check that the value given is valid:
if (is_numeric($_GET['id']) && $_GET['id'] >0 ){
$id = (int)$_GET['id'];
}
This is simple code to check the value passed from the link is a integer number. Never trust user input.
It is also a good idea never to directly plug in GET and POST values into your SQL statements. Hence I've copied the value across to $id
Part 3:
$sql = "UPDATE <TABLE> SET STOCK = STOCK-1 WHERE Product_ID = ? LIMIT 1";
The table name is your table name, the LIMIT 1 simply ensures this only works on one row, so it will not effect too many stocked games.
That above is the SQL but how to make that work in PHP:
first off, the statement needs to be prepared, then once prepared, the value(s) are plugged into the ? parts (this is MySQLi syntax, PDO has the more useful :name syntax).
So:
include "database.php"; ////include file
$dataBase = new database(); ///create new instance of class.
if (is_numeric($_GET['id']) && $_GET['id'] >0 ){
$id = (int)$_GET['id'];
$sql = "UPDATE <TABLE> SET STOCK = STOCK-1 WHERE Product_id = ? LIMIT 1";
$update = $dataBase->dbLink->prepare($sql);
$update->bind_param("i",$id);
$update->execute();
$counter = $update->affected_rows;
$update->close();
//////gap for later work, see below:
}
else
{
print "Sorry nothing to update";
}
There's probably quite a lot going on here, first off the bind_param method sets the values to plug into the SQL query, replacing the ? with the value of $id. The i indicates it is meant to be an Integer value. Please see http://php.net/manual/en/mysqli-stmt.bind-param.php
The $counter value simply gets a return of the number of affected rows and then something like this can be inserted:
if ($counter > 0 ){
print "Thank you for your order. Stock has been reduced accordingly.";
}
else {
print "Sorry we could not stock your order.";
}
Part 4
And finally if you wish you can then just output the print messages or I tend to put the messages into a SESSION, and then redirect the PHP page back.
I hope this has helped a bit. I would highly recommend if you're not used to the database interactions in this way then either use PDO or MySQLi but do not combine the two, that will cause all sorts of syntax faults. Using MySQLi means that everything you know MySQL can do, is done better with the addition of the letter "i" in the function call. It is also very good for referencing the PHP.net Manual which has an excellent clear detailed examples of how to use each PHP function.
The best is to set a link on each button with the ID of your game (1 for destiny, 2 for Fifa15).
Then your script which the user will launch by clicking will be :
<?php
include('database.php'); // your database connection
if($_GET['id']) {
$id=$_GET['id'];
} else throw new Exception('Invalid parameter');
$statement = myPDO::getInstance->prepare(<<<SQL
UPDATE TABLE
SET STOCK = STOCK-1
WHERE Product_id = :id
SQL
);
$statement->execute(array(":id" => $id));
This script will do the job

html button to reset field in mysql database using php

Kinda new to mysql and php
I have a hit counter for each page on my site and a private page that list all pages and hits.
I have a button that will reset all pages to zero and next to each page listing I have a reset button that will reset each page individually. This all was using a text file but now I am swtching to mysql database. I have coded the "RESET ALL" button to work but can not get the individual page buttons to work.
the processing code is:
if($_POST[ind_reset]) {
$ind_reset = $_POST[ind_reset];
mysql_connect("server", "username", "password") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
$sql = 'UPDATE counters SET Hits =\'0\' WHERE Page = \'$ind_reset\';';
}
and the html form code is a string:
$page_reset = "<form id='Reset' action='counter_update.php' method='post'>
<button type='submit' name='ind_reset' value='$formPage'>RESET</button>
</form>";
Let's start with the first thing:
if($_POST[ind_reset]) {
should be
if($_POST['ind_reset']) {
It works without quotes because PHP is silently correcting your error. If you turned error reporting to E_ALL, you would get to see the error message.
One thing that you need to consider is that you can never trust POST data to be what you think it's supposed to be. Maybe you put in a typo. Maybe a hacker is sending you fake POST data. Whichever it is, it will mess up your code if the wrong thing gets put in that database update. For this reason, instead of simply plugging in that POST value into your database, you should have a checker to make sure that the value is a valid one. When I do things like this, I make an array of possible values and use only those values when updating or inserting into the database. Example:
$pages = array('value_on_page'=>'value_put_in_database',
'xyz'=>'thing_in_database_2');
//the valid things to post are either 'value_on_page' or 'xyz',
//but what goes into the database are the values those keys point to
//e.g. if $_POST['ind_reset'] == 'xyz', $ind_reset will be 'thing_in_database_2'
$key = $_POST['ind_reset'];
if(!isset($pages[$key])) {
//if that posted value isn't a key in the array, it's bad
error_log('Invalid posted page'.$key);
} else {
//this is a valid posted page
$ind_reset = $pages[$key];
//** do the database stuff right here in this spot **//
}
Now, for the reason your posted code doesn't work, you are missing the final, crucial part of doing a database query: the part where you actually run the query.
$conn = mysql_connect("server", "username", "password") or error_log(mysql_error());
mysql_select_db("database") or error_log(mysql_error());
$sql = 'UPDATE counters SET Hits =\'0\' WHERE Page = \'$ind_reset\';';
mysql_query($sql, $conn) or error_log(mysql_error());
I hope you have noted that I replaced "die" with "error_log." If you do error_log(mysql_error(), 1, 'youremail#example.com'), it will email it to you. Otherwise, as with in my examples, it gets put into wherever your system's error log file is. You can then have a nice history of your database errors so that, when you inevitably return to StackOverflow with more questions, you can tell us exactly what's been going on. If you use a file, just make sure to either rotate the error log file's name (I name them according to the day's date) or clear it out regularly, or it can get really, really long.
Using the mysqli code you posted in your comment is a better idea than the mysql_* functions, but you don't quite have it correct. The "bind_param" part sticks your variable into the spot where the question mark is. If your variable is a string, you put "s" first, or if it's an integer, you put "i" first, etc. And make sure you close things once you're done with them.
$db = new mysqli("server", "username", "password", "database");
if(!$db->connect_errno) {
$stmt = $db->prepare("UPDATE counters SET Hits = '0' where Page = ?");
$stmt->bind_param('s',$ind_reset); //assuming $ind_reset is a string
if(!$stmt->execute()) {
error_log($stmt->error);
}
$stmt->close();
} else {
error_log($db->connect_error);
}
$db->close();

Is there a way to insert cookies into a database?

I need to match up a users name with a value inside a database, so I want to insert the users name that is saved in a cookie. The function is pretty simple. The cookie is stored correctly and I can echo it. My insert script also works cause I can insert other things. But for some reason I cannot insert a cookies value.
This is pretty much what I'm trying to do:
$username = $_COOKIE['username'];
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
or die('error');
$query1 = "INSERT INTO Gallery (username) VALUES('$username')";
$data1 = mysqli_query ($dbc, $query1) or die('error1');
mysqli_close($dbc);
Is there something I'm missing? I tried using sessions, but no luck.
I also made the cookie accessible throughout the whole domain.
There are (at least) two problems here.
You copy the value of the cookie to a variable called $user but use a variable called $username to try to insert data into the database
You don't perform any kind of sanity check on the cookie data (which is data provided by the browser and thus tainted) before using in an SQL query. This is an invitation to Little Bobby Tables.
Possibly try changing your query to this...
$query1 = "INSERT INTO Gallery (username) VALUES(" . mysql_escape_string($_COOKIE['username']) . ")";

Categories