PHP/MySQL - Not posting to database - php

This PHP script is meant to post a users name into a database but it doesnt seem to work properly. The project in unity wont post it correctly and going straight to IP
ADDRESS/addUser.php?NAME=Ryan
also doesnt work. It auto increments the ID as it should but the name field is always blank.
<?php
//Connect
$sql_connect = mysql_connect("IP", "USER", "PASS") or die ("no DB Connection");
//Select Database
mysql_select_db("practiceCrim") or die ("DB not found");
//Post Info To Var
$name = $_POST['NAME'];
//Query
$query = "INSERT INTO Users (Name)
VALUES ('$name')";
//Run The Query, Get Result
$result = mysql_query( $query, $sql_connect );
//Not Really Needed For You
if(!$result)
{
die('Error: ' . mysql_error());
}
//Close The Connection
mysql_close($sql_connect);
?>

It look like you're getting the name field from the PHP $_POST variable. But your example passes the name field as a GET parameter.
To fix this, you have two options. If you only want to allow name to be passed as a GET parameter, then you need to do this:
$name = $_GET["NAME"];
If you want to allow name to be passed as either a GET or a POST parameter, you can do this:
$name = $_REQUEST["NAME"];

you should replace $name = $_POST['NAME'] with $name = $_GET['NAME'] or $name = $_REQUEST['NAME']
where $_REQUEST is default but don't use $_REQUEST

Related

mysql problem using php when update table

This system is based on invitation codes, if u have a code that is present in the database you can submit the input therefore change a value in a row. There are 2 inputs, 1) Invitation Code (key), if exist in the database the user can submit the value 2)Name (user). I done the following code but it doesn't work, any suggestions?
<?php
//get value pass from form in login.php
$username = $POST['user'];
$password = $POST['key'];
//connect to the server and select database
mysql_connect("localhost", "...","...");
mysql_select_db("...");
// Query the database for user
$result = mysql_query("UPDATE invitation_keys SET name ='$username' WHERE key = '$password'";)
or die("Failed to query database".mysql_error());
$row = mysql_fetch_array($result);
if ($row['key'] == $password) {
echo "Login success!!!".$row['key'];
} else {
echo "Failed to login";
}
?>
When you are coding in PHP, var_dump($var) is your best friend.
So the first thing to do here, is to print the query.
You will see, that your $username and $password vars are NULL, because you missed the syntax of $_POST[].
After, you can put in var_dump what you want, and that's why its interesting, because you will debug faster with this.

mysql UPDATE query does not run

I want to update information. when I use the below in code is not working what is wrong in my code:
if(isset($_POST['submit'])){
$sql = "UPDATE `food`.`food_item`
SET `food_name` = '$_POST[food_name]',
`food_price` = '$_POST[food_price]',
`food_cat` = '$_POST[food_category]'
WHERE `food_item`.`id` ='$_POST[id]';";
$result = mysql_query($sql) or die("query not");
header("Location: product_info.php") ;
}
If you have a form input like,
<input type="text" name="product_name" />
You should get the value by,
$_POST['product_name'];
Is your form method is POST for GET?
If your method type is POST, you should get it like $_POST['input_name']
If your method type is GET, you should get it like $_GET['input_name']
Does all your input name you mentioned in html matches in php code?
Eg : If you have a form with input type,
<input type="text" name="product_name" />
Then, in php code, you should get it with what you entered in name attribute
$_POST['product_name'] OR $_GET['product_name']
Not something like,
$_POST['prod_name'] OR $_GET['prod_name']
Try this,
if(isset($_POST['submit'])
{
$food_name = $_POST['food_name'];
$food_price = $_POST['food_price'];
$food_cat = $_POST['food_category'];
$id = $_POST['id'];
// do not directly input the form data to sql, filter it by a special function mysqli_real_escape_string
// eg : $food_price = mysqli_real_escape_string($db, $_POST['food_price']);
// before executing the query, try to echo the each form input and sql query for clear picture.
$sql = "UPDATE `food`.`food_item` SET `food_name` = '$food_name',`food_price` = '$food_price',`food_cat` = '$food_cat' WHERE `food_item`.`id` ='$id'";
$result = mysqli_query($db, $sql);
if($result)
{
//header("Location: product_info.php") ;
echo "success";
}
else
{
echo "fail";
}
}
else
{
echo "form not submitted";
// use header to redirect to old page again
}
WARNING :
mysql is deprecated. Use mysqli or PDO.
Note :
$db is a database connection variable. You need to setup like
$db = mysqli_connect("localhost","username","password","database_name");
Look it's not mysql_connect, its mysqli_connect. Replace the db value according to your needs.
You can try following code to find the error.
echo mysql_error(); exit;
after following code.
$result = mysql_query($sql)
In order to access the array variables inside double quoted string, either do by enclosing them in curly brackets or put it outside the double quotes and append as a string. Here you try adding curly brackets like this:
if(isset($_POST['submit'])){
$sql = "UPDATE `food`.`food_item`
SET `food_name` = '{$_POST['food_name']}',
`food_price` = '{$_POST['food_price']}',
`food_cat` = '{$_POST['food_category']}'
WHERE `food_item`.`id` ='{$_POST['id']}';";
$result = mysql_query($sql) or die("query not");
header("Location: product_info.php") ;
}
Just echo $sql; Check what are the actual values in the query. Copy & run it in MYSQL query.
I think that you applied back ticks () on field names food_name . Remove back ticks & replace it with single quote ( ' )

Trouble having passed GET variable display on target page

I'm going crazy here. I have two pages. Page A and Page B. I simply want to set a variable in Page A, pass it to Page B via GET method (URL) and then have code display the variable. I do not get any errors, but the the variable simply will not display. Here is the code:
Page A:
print "" .$name . "<br>";
Page B:
<?php
//db connect info above not shown
$password = "*****";
$usertable = "stories";
$myfield = (int) $_GET['id'];
//Connect to db
mysql_connect($hostname, $username, $password) OR DIE ("Unable to
connect to database! Please try again later.");
mysql_select_db($dbname);
//Fetch from db
$query = "SELECT * FROM stories where story_id = $myfield";
$result = mysql_query($query);
echo "TEXT: ";
if ($result) {
while($row = mysql_fetch_array($result)) {
$name = $row["story_id"];
echo $name;
}
}
?>
All I get returned is "TEXT:"
But it want it to show "TEXT: 4" (because I know 4 is the story_id from page a. I even see the 4 in the URL of page B being successfully passed, but can't get it to display here.
As a second part of the question, my REAL GOAL is not to simply print the story_id, but rather the story text itself (a paragraph of text). This variable is in the same table called story_text. It seems a pipe dream to get the actual story text to display when I can't even simply have the story_id number print as a test.
Please help!
if your url is
http://mysite.net/page-b?var=".$id ."\"
The variable passed will be $var, not $id
$myfield = (int) $_GET['id']; // WRONG
$myfield = (int) $_GET['var']; // RIGHT
Your statement
$myfield = (int) $_GET['id'];
this should be
$myfield = (int) $_GET['var'];

SQL WHERE ID carryover

Basically I've created two php papes. One selects my entire table, and displays just date, and id number from it. Each date has a link directing to a display.php file. It pulls the ID number with it to the next display.php page. What I want to do on the display.php file is to display the entire row using that PHP.
So I know that Select * from tablename WHERE id=1 will pull that data, but how to get the ID number into there WHERE statement?
This is the main page code:
// SQL query
$strSQL = "SELECT * FROM table1";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
while($row = mysql_fetch_array($rs)) {
// DATE
$strName = $row['date'];
// Create a link to display.php with the id-value in the URL
$strLink = "<a href = 'display.php?ID = " . $row['ID'] . "'>" . $strName . "</a>";
// List link
echo "<li>" . $strLink . "</li>";
}
That code links works and goes to display.php.
How would I create the link using the ID number pulling with it. Would I use a post command?
$id= Post['id']
then WHERE id = '$id'
?
TBH I did try that and got nothing. Any suggestions?
USING GET now...still not luck
I've tried the GET statement. In my address bar it shows the ID number. So I see the ID number pulling over with it. I tried even just echoing the ID to see if maybe it was just my code messing up.
<?php
$dbhost = 'localhost';
$dbuser = 'myusername';
$dbpass = 'mypw';
$dbname = 'mydbname';
$id = $_GET['id'];
mysql_connect($dbhost, $dbuser, $dbpass) or die('MySQL connect failed. ' . mysql_error());
mysql_select_db($dbname) or die('Cannot select database. ' . mysql_error());
?>
<body>
ID #<?php echo $id ?>
</body>
</html>
<body>
ID #<?php echo $id ?>
</body>
</html>
Still no luck
So in your display file you'd do something like this
$id = $_GET['ID'];
//DO SANITIZATION ETC ON THE ID HERE TO MAKE SURE ITS SOMETHING WE EXPECTED (AN INT)
$sql = "SELECT STUFF WHERE ID = {$id}"; //FOR BREVITY SAKE DOING AWAY WITH SECURITY
So basically what your first script is doing is passing the id in the url query string, values passed here are accessible in the $_GET super globals array.
Anything you access in here and the other super globals should be treated as completely dangerous to your application. You should filter and escape the hell out of it, and then before inserting it into the database you must escape it using the correct mechanism for your database. Otherwise you leave yourself open to SQL injection attacks.
Values passed in the querystring use GET not POST.
Post is for form variables.
You should also be aware of the danger of a SQL injection attack when taking values from the querystring.

PHP - Dynamic SQL Query from Dynamic POSTs

First time question, long time reader :)
I am building forms dynamically from Columns in a MYSQL DB. These columns
are created/ deleted etc.. elsewhere on my App. My form runs a query against a
SQL View and pulls in the column names and count of columns. Simple! build the form,
with the HTML inputs built with a PHP for loop, and it echos out the relevant HTML for the new form fields. All very easy so far.
Now i want a user to update these dynamically added fields and have the data added to the relevant columns - same table
as existing columns. So, as the input fields are named the same as the columns, they are posted to a PHP script for processing.
Problem is, while i have the actual field names inserted in to the SQL INSERT query, i cannot figure out how to extract the POST
data from the POST dynamically and add this to the VALUEs section of the query.
Here is my attempt....
The Query works without the variables added to it.
It works like this, first section/ is to retrieve the columns names from earlier created VIEW - as these are identical to POST names from the form. Then output to array and variable for insertion to Query. It looks like the implode function works, in that the relevant column names are correct in the statement, but i fear that my attempt to inject the column names on to the POST variables is not working.
$custq = "SELECT * FROM customProperties";
$result = $database->query($custq);
$num_rows = mysql_numrows($result);
while (list($temp) = mysql_fetch_row($result)) {
$columns[] = $temp;
}
$query = '';
foreach($columns as $key=>$value)
{
if(!empty($columns[$key]))
{
$values .= "'".'$_POST'."['".$value."'], ";
}
}
$q = "INSERT INTO nodes
(deviceName,
deviceInfo,
".implode(", ", $columns).",
nodeDateAdded,
status
)
VALUES
('" . $_POST['deviceName'] . "',
'" . $_POST['deviceInfo'] . "',
".$values."
CURDATE(),
'1'
)";
$result = $database->query($q)
Any help is much appreciated. I will feed back as much as i can. Please note, relativity new to PHP, so if i am all wrong on this, i will be glad for any tips/ advice
Regards
Stephen
If you want to get the values of every POST input without knowing the input names then you can do it this way:
//get all form inputs
foreach($_POST as $name => $value)
{
echo $name . " " . $value . "<br>";
}
If you want to get the value of certain POST inputs where you know the name of the input field then you can do it this way:
if(isset( $_GET["deviceName"]))
{
$deviceName = $_POST["deviceName"];
}
if(isset( $_GET["deviceInfo"]))
{
$deviceInfo = $_POST["deviceInfo"];
}
To connect to a database and insert the info then you have to do something like this:
$host = "localhost";
$dbuser = "username";
$pass = "password";
$datab = "databasename";
//Create DB connection
$con=mysqli_connect($host, $dbuser, $pass,$datab);
if (mysqli_connect_errno($con))
{
echo "ERROR: Failed to connect to the database: " . mysqli_connect_error();
}
else
{
echo "Connected to Database!";
}
//insert into database
mysqli_query($con, "INSERT INTO nodes (deviceName, deviceInfo) VALUES ('$deviceName', '$deviceInfo')");
(Don't forget to add mysql_real_escape_string to the $_POST lines after you get it working.)

Categories