I'm having a slight issue and I'm not sure why. Maybe someone can help me out. First a few disclaimers; I'm still learning PHP, I'm aware of mysqli or pdo but the server this will live on is running an old ver 4 of php.
Ok now on to the problem.
I have a form which passes to my post-data.php form to push to SQL db.
However when it pushes the data it's only pushing the variables not the data within the vars from post action of the form.
Screenshot of submitted data in PHPmyadmin
My Code follows:
<?php
$hostname = "localhost"; $username = "goldme_owner";
$dbName = "goldme_dealer_meeting";
$connect = mysql_connect($hostname, $username);
if (!$connect) {
echo "Please try later.";
}
else {
mysql_select_db($dbName, $connect);
$checkboxA1 = isset($_POST['checkboxA1']) ? $_POST['checkboxA1'] : 'No';
$checkboxE1 = isset($_POST['checkboxE1']) ? $_POST['checkboxE1'] : 'No';
$checkboxF1 = isset($_POST['checkboxF1']) ? $_POST['checkboxF1'] : 'No';
$checkboxG1 = isset($_POST['checkboxG1']) ? $_POST['checkboxG1'] : 'No';
$checkboxH1 = isset($_POST['checkboxH1']) ? $_POST['checkboxH1'] : 'No';
$checkboxI1 = isset($_POST['checkboxI1']) ? $_POST['checkboxI1'] : 'No';
$checkboxJ1 = isset($_POST['checkboxJ1']) ? $_POST['checkboxJ1'] : 'No';
$checkboxK1 = isset($_POST['checkboxK1']) ? $_POST['checkboxK1'] : 'No';
}
echo "$checkboxA1"; //just want to make sure checkbox vars are passing //will delete in final code
echo "$checkboxE1"; //just want to make sure checkbox vars are passing //will delete in final code
echo "$checkboxF1"; //just want to make sure checkbox vars are passing //will delete in final code
echo "$checkboxG1"; //just want to make sure checkbox vars are passing //will delete in final code
echo "$checkboxH1"; //just want to make sure checkbox vars are passing //will delete in final code
echo "$checkboxI1"; //just want to make sure checkbox vars are passing //will delete in final code
echo "$checkboxJ1"; //just want to make sure checkbox vars are passing //will delete in final code
echo "$checkboxK1"; //just want to make sure checkbox vars are passing //will delete in final code
echo "$_POST[confirm]"; //just want to make sure confirm code generated //will delete in final code
$sql_statement = 'INSERT INTO 2014_registrations'.
'(confirm_number,timecode,company_name,country,address1,address2,city'.
',state,zip,phone,fax,email,zone_manager,transport,first_name,'.
'last_name,tuesday_tours,tuesday_meat,wed_lunch,wed_dinner,'.
'wed_pool_tourney,thurs_lunch,thurs_dinner,fri_shop,fri_tour,dietary)'.
'VALUES ("$_POST[confirm]","$_POST[timecode]","$_POST[company_name]",'.
'"$_POST[address]","$_POST[address2]","$_POST[city]","$_POST[state]",'.
'"$_POST[zip]","$_POST[country]","$_POST[phone]","$_POST[fax]",'.
'"$_POST[email]","$_POST[zonemanager]","$_POST[transport]",'.
'"$_POST[fattendee1]","$_POST[lattendee1]","$_POST[checkboxA1]",'.
'"$_POST[radio1]","$_POST[checkboxE1]","$_POST[checkboxF1]",'.
'"$_POST[checkboxG1]","$_POST[checkboxH1]","$_POST[checkboxI1]",'.
'"$_POST[checkboxJ1]","$_POST[checkboxK1]","$_POST[dietary1]")';
$rec_insert = mysql_query($sql_statement);
if(! $rec_insert ){
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($connect);
?>
Inside single quotes the variables are not read as variables. For example echo '$a' will print $a but echo "$a" will print the value of $a.
In your code you are trying to use something similar to '$a', or in other words you are using single quotes around variables instead of double quotes.
Try writing it as
"VALUES ('$_POST[confirm]','$_POST[timecode]','$_POST[company_name]',".
or
'VALUES ("'.$_POST[confirm].'","'.$_POST[timecode].'","'.$_POST[company_name].'",'.
and so on..
Note that the use of $_POST[confirm] gives an notice. The correct way to use it is $_POST['confirm'].
Also note that your code is vulnerable to SQL injections. Consider using prepared statements.
The variables are being read as strings because they're written in single quotes.
I've moved the variables to outside of the single quotes and just concatenated them to the string. This code is extremely susceptible to SQL injection and should not be used in a production environment.
$sql_statement = 'INSERT INTO 2014_registrations'.
'(confirm_number,timecode,company_name,country,address1,address2,city'.
',state,zip,phone,fax,email,zone_manager,transport,first_name,'.
'last_name,tuesday_tours,tuesday_meat,wed_lunch,wed_dinner,'.
'wed_pool_tourney,thurs_lunch,thurs_dinner,fri_shop,fri_tour,dietary)'.
'VALUES ("'.$_POST[confirm].'","'.$_POST[timecode].'","'.$_POST[company_name].'",'.
'"'.$_POST[address].'","'.$_POST[address2].'","'.$_POST[city].'","'.$_POST[state].'",'.
'"'.$_POST[zip].'","'.$_POST[country].'","'.$_POST[phone].'","'.$_POST[fax].'",'.
'"'.$_POST[email].'","'.$_POST[zonemanager].'","'.$_POST[transport].'",'.
'"'.$_POST[fattendee1].'","'.$_POST[lattendee1].'","'.$_POST[checkboxA1].'",'.
'"'.$_POST[radio1].'","'.$_POST[checkboxE1].'","'.$_POST[checkboxF1].'",'.
'"'.$_POST[checkboxG1].'","'.$_POST[checkboxH1].'","'.$_POST[checkboxI1].'",'.
'"'.$_POST[checkboxJ1].'","'.$_POST[checkboxK1].'","'.$_POST[dietary1].'")';
First of all, inserting data directly into the db from POST request is almost never a good idea.
I know this is really badly formatted, but try using this $sql_statement instead:
$sql_statement = 'INSERT INTO 2014_registrations'.
'(confirm_number,timecode,company_name,country,address1,address2,city'.
',state,zip,phone,fax,email,zone_manager,transport,first_name,'.
'last_name,tuesday_tours,tuesday_meat,wed_lunch,wed_dinner,'.
'wed_pool_tourney,thurs_lunch,thurs_dinner,fri_shop,fri_tour,dietary)'.
"VALUES (\"{$_POST[confirm]}\",\"{$_POST[timecode]}\",\"{$_POST[company_name]}\",".
"\"{$_POST[address]}\",\"{$_POST[address2]}\",\"{$_POST[city]}\",\"{$_POST[state]}\",".
"\"{$_POST[zip]}\",\"{$_POST[country]}\",\"{$_POST[phone]}\",\"{$_POST[fax]}\",".
"\"{$_POST[email]}\",\"{$_POST[zonemanager]}\",\"{$_POST[transport]}\",".
"\"{$_POST[fattendee1]}\",\"{$_POST[lattendee1]}\",\"{$_POST[checkboxA1]}\",".
"\"{$_POST[radio1]}\",\"{$_POST[checkboxE1]}\",\"{$_POST[checkboxF1]}\",".
"\"{$_POST[checkboxG1]}\",\"{$_POST[checkboxH1]}\",\"{$_POST[checkboxI1]}\",".
"\"{$_POST[checkboxJ1]}\",\"{$_POST[checkboxK1]}\",\"{$_POST[dietary1]}\")";
Your `sql_statment is wrong.
$sql_statement = 'INSERT INTO 2014_registrations'.
'(confirm_number,timecode,company_name,country,address1,address2,city'.
',state,zip,phone,fax,email,zone_manager,transport,first_name,'.
'last_name,tuesday_tours,tuesday_meat,wed_lunch,wed_dinner,'.
'wed_pool_tourney,thurs_lunch,thurs_dinner,fri_shop,fri_tour,dietary)'.
'VALUES ("$_POST[confirm]","$_POST[timecode]","$_POST[company_name]",'.
'"$_POST[address]","$_POST[address2]","$_POST[city]","$_POST[state]",'.
'"$_POST[zip]","$_POST[country]","$_POST[phone]","$_POST[fax]",'.
'"$_POST[email]","$_POST[zonemanager]","$_POST[transport]",'.
'"$_POST[fattendee1]","$_POST[lattendee1]","$_POST[checkboxA1]",'.
'"$_POST[radio1]","$_POST[checkboxE1]","$_POST[checkboxF1]",'.
'"$_POST[checkboxG1]","$_POST[checkboxH1]","$_POST[checkboxI1]",'.
'"$_POST[checkboxJ1]","$_POST[checkboxK1]","$_POST[dietary1]")';
Change to:
$sql_statment = "INSERT INTO 2014_registrations".
"(confirm_number,timecode,company_name,country,address1,address2,city".
",state,zip,phone,fax,email,zone_manager,transport,first_name,".
"last_name,tuesday_tours,tuesday_meat,wed_lunch,wed_dinner,".
"wed_pool_tourney,thurs_lunch,thurs_dinner,fri_shop,fri_tour,dietary)".
"VALUES ($_POST['confirm'],$_POST['timecode'],$_POST['company_name'],".
"$_POST['address'],$_POST['address2'],$_POST['city'],$_POST['state'],".
"$_POST['zip'],$_POST['country],$_POST[phone'],$_POST['fax'],".
"$_POST['email'],$_POST['zonemanager'],$_POST['transport'],".
"$_POST['fattendee1'],$_POST['lattendee1'],$_POST['checkboxA1'],".
"$_POST['radio1'],$_POST['checkboxE1'],$_POST['checkboxF1'],".
"$_POST['checkboxG1'],$_POST['checkboxH1'],$_POST['checkboxI1'],".
"$_POST['checkboxJ1'],$_POST['checkboxK1'],$_POST['dietary1']")";
If you are using $sql_statment = '' you cant put a variable in $sql_statment = '$_POST[confirm]'; because it will treat it like a text. You have to make it like $sql_statment = $_POST['checkboxG1'].','.$_POST['checkboxH1'].','.$_POST['checkboxI1'].','.
Another way is to change it all to $sql_statment = "$_POST['checkboxG1'],$_POST['checkboxH1'],$_POST['checkboxI1'],"; like I did.
See that there is a differance in using ' and ";
Btw. you should use some security for example mysql_escape_string.
Related
I am attempting to create a function that will insert items (and will do the same to edit) items in a database through a form. I have the form and the PHP - and when I run the function, I get the correct database name to pull and the variable names to pull along with the values I input, but I then see a database error? Any help would be great (I'm still newer to PHP really and pulling out some hair)
Config File:
$hostname = 'localhost';
$username = 'DEFINED';
$password = 'DEFINED';
$database = 'DEFINED';
$table = 'recipes';
require('../config.php');
$link = mysql_connect($hostname,$username,$password);
mysql_select_db($database,$link);
/* Get values and submit */
$rid = mysql_real_escape_string($_POST['rid']);
$name = mysql_real_escape_string($_POST['name']);
$category = mysql_real_escape_string($_POST['category']);
$tags = mysql_real_escape_string($_POST['tags']);
$search_tags = mysql_real_escape_string($_POST['search_tags']);
$description = mysql_real_escape_string($_POST['description']);
$description2 = mysql_real_escape_string($_POST['description2']);
$recipeAbout = mysql_real_escape_string($_POST['recipeAbout']);
$ingredients_1 = mysql_real_escape_string($_POST['ingredients_1']);
$directions_1 = mysql_real_escape_string($_POST['directions_1']);
$query = "INSERT INTO $table (name, category, tags, search_tags, description,description2, recipeAbout, ingredients_1,directions_1) VALUES ('$name','$category','$description','$description2' $tags','$search_tags','$description','$recipeAbout','$ingredients_1','$directions_1')";
echo $query;
Besides the missing comma in '$description2' $tags' => '$description2', $tags' which you said had been added afterwards, and signaled by Ryan: there's also a missing quote, so change it to '$description2', '$tags' and having 2x '$description' variables, remove one.
VALUES
('$name','$category','$tags','$description','$description2', '$search_tags','$recipeAbout','$ingredients_1','$directions_1')";
However, the most important part to querying, is that you must use mysql_query() which you are not using => mysql_query() which is why data isn't being inserted, once you've fixed the syntax errors.
mysql_query() is the essential part.
Add the following to your code:
if(mysql_query($sql,$link)){
echo "Success";
}
else{
echo "Error" . mysql_error();
}
Plus, use prepared statements, or PDO with prepared statements.
You're using a deprecated library and open to SQL injection..
Plus make sure you have assigned $table to the table you wish to enter data into. It's not shown in your question.
You also did not show what your HTML form contains. Make sure that you are using a POST method and that all elements are named with no typos.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
Sidenote: Error reporting should only be done in staging, and never production.
EDIT: and using mysqli_
As a quick test, try the following and replacing the values in the line below with your own.
<?php
$link = mysqli_connect("host","username","password","database")
or die("Error " . mysqli_error($link));
$table = "recipes";
$name = mysqli_real_escape_string($link,$_POST['name']);
mysqli_query($link,"INSERT INTO `$table` (`name`) VALUES ('".$name."')")
or die(mysqli_error($link));
?>
If that still does not work, then you need to check your database, table, column name(s), including types and column lengths.
Lot's of stuff wrong here...
You're missing a quote on the second of these two items, as well as either a string concat or a comma: '$description2' $tags'
You've also got your order messed up for tags, search tags, and description 1/2.
$description is in there twice (you have 9 columns defined and 10 values in your statement)
You don't seem to have declared a value for $table
As Fred -ii- has pointed out in his answer, you're missing mysql_query() to actually run it. I assumed you have it further down in your code, but it's missing from the post, which is causing some confusion...
Also, consider updating to use mysqli instead of mysql functions.
what are you echoing $query for?
You do not have any reason to do that except if you just want to use it as a string variable.
it should be mysql_query($query);
What is the exact "database error" error you are getting?
I suggest reading this article about PDO
If you can't insert the data correctly, this might be your problem too.
I'm having trouble getting info from my MySQL database.
Here is my code :
/********************
* Database Info
********************/
$host = "localhost";
$user = "admin";
$pass = "admin#";
$database = "db_admin";
/********************
* Database connection
********************/
$con = mysqli_connect( $host, $user, $pass, $database );
if (mysqli_connect_errno ()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error ();
}
$result = array();
if (isset($_POST['ID'])) {
$id = $_POST['ID'];
$query = "SELECT * FROM Servers WHERE PID='" .$id. "'";
$result = mysqli_query($con, $query);
}
print("<pre>".print_r($result,true)."</pre>");
My first question, Did I use "isset" function currectly?
Because it doesnt seem like it is actually going though the if statement.
The Url I am using is : #..com/view.php?ID=1
My second question, Did I use the $query correctly?
Because I echo $id and that echoed out a "MySQL Object()"
Finally, the print printed out "Array()"
I'm just starting on PHP, Thanks for the help :)
A few things:
If you're passing the variable in the query string, use $_GET instead of $_POST to retrieve the values.
$result will return an pointer to the recordset, not the rows themselves. You will have to use mysqli_fetch_array() to fetch the rows.
ADD:
If you are sure that you will only have 1 record returning, you can use:
$row = mysqli_fetch_assoc($query);
echo $row['field_name'];
More then 1 record?
while($row = mysqli_fetch_assoc($query)){
echo $row['field_name'];
}
# your first question: if you have a input field with the name="ID", then its good.
Please also post your HTML :)
$var = 'Hello world';
if(isset($var)){ //If the var $var has been set (in this case it is)
echo $var;
} else {
//If $var is not set, then we get in the else
echo 'The var $var is not set';
}
The best thing is debugging the code with a debugger, you may use XDebug, or at least use var_dump(); to see what happens
var_dump($_REQUEST, $result);
Answer to your first question: It's hard to say if you've used it correctly when you haven't said what you're trying to do. I'm presuming that you only want run the code enclosed in the if-statement if the POST variable 'ID' has been received. If so, yes you've done it correctly.
Answer to your second question: I'm presuming on this line you're trying to build a string with a valid MySQL query. You've done that correctly, assuming $_POST['ID'] is a string (or can be converted to a string, see http://www.php.net/manual/en/language.types.string.php#language.types.string.casting).
If you're echoing $id and it's returning an object, however, you'll have a problem. You can't combine a string and an object like that. You'd need to iterate the object with a foreach, for example, and extract the id from that. The rest of the code won't work until that part is resolved.
The thing to investigate now is why $_POST['ID'] is returning an object. You'll need to provide the form code at the very least.
I am really trying to wrap my head around this and failing miserably. What I want to do it build a MySQL query based on the URL parameters passed by the URL. I am trying to create a re usable dynamic script that can do what it needs to do based on the URL parameter.
This is what I have come up with, and it appears that it does what it is supposed to do (no errors or anything) but nothing actually gets inserted in the database. I know somewhere I have made a dumb mistake (or thought something out wrong) so hopefully one of you guys can point me in the right direction.
Thanks!
//List all possible variables you can expect the script to receive.
$expectedVars = array('name', 'email', 'score', 'age', 'date');
// This is used for the second part of the query (WHERE, VALUES, ETC)
$fields = array('uName','uEmail','uScore','uAge','uDate');
// Make sure some fields are actually populated....
foreach ($expectedVars as $Var)
{
if (!empty($_GET[$Var]))
{
$fields[] = sprintf("'%s' = '%s'", $Var, mysql_real_escape_string($_GET[$Var]));
}
}
if (count($fields) > 0)
{
// Construct the WHERE Clause
$whereClause = "VALUES " . implode(",",$fields);
//Create the SQL query itself
$sql = ("INSERT INTO $mysql_table ($fields) . $whereClause ");
echo "1"; //It worked
mysql_close($con);
}
else
{
// Return 0 if query failed.
echo "0";
}
?>
You missed mysql_query($sql):
if(!mysql_query($sql)){
//die(mysql_error());
}
Please consider to use PDO or My SQLi using parametrize query because mysl_* function depreciated.
Your SQL is all wrong. You're using the field = value syntax for an INSERT, then you're concatenating an array as if it were a string ($fields), and you're missing a couple of parentheses around the values.
a couple of things: i've found for php <-> mysql its important to see what's going into mysql and experiement directly with those queries in phpmyadmin when i get stuck.
1 - in my code I output mysql_error() when the query fails or when a debug flag is set. this usually explains the sql issue in a way that can point me to a misspelled field name etc...
2 - this way i can feed that mysql query directly into phpmyadmin and tweak it until it gives me the results i want. (while i'm there i can also use explain to see if i need to optimize the table)
specifics in your code. unlike C languages sprintf is implied. here's how i'd write your code:
// List all possible variables you can expect the script to receive.
$expectedvars = array('name', 'email', 'score', 'age', 'date');
// This is used for the second part of the query (WHERE, VALUES, ETC)
// $fields = array('uName','uEmail','uScore','uAge','uDate');
$fields = array();
// Set only the variables that were populated ...
foreach ($expectedvars as $var) {
if (!empty($_GET[$var])) {
$name = "u" + ucwords($var); // convert var into mysql field names
$fields[] = "{$name} = " . mysql_real_escape_string($_GET[$var]);
}
}
// only set those fields which are passed in, let the rest use the mysql default
if (count($fields) > 0) {
// Create the SQL query itself
$sql = "INSERT INTO {$mysql_table} SET " . implode("," , $fields);
$ret = mysql_query($sql);
if (!$ret) {
var_dump('query_failed: ', $sql, $ret);
echo "0"; // Query failed
} else {
echo "1"; // It worked
}
} else {
// Return 0 if nothing to do
echo "0";
}
mysql_close($con);
I'm trying to create an update function in PHP but the records don't seem to be changing as per the update. I've created a JSON object to hold the values being passed over to this file and according to the Firebug Lite console I've running these values are outputted just fine so it's prob something wrong with the sql side. Can anyone spot a problem? I'd appreciate the help!
<?php
$var1 = $_REQUEST['action']; // We dont need action for this tutorial, but in a complex code you need a way to determine ajax action nature
$jsonObject = json_decode($_REQUEST['outputJSON']); // Decode JSON object into readable PHP object
$name = $jsonObject->{'name'}; // Get name from object
$desc = $jsonObject->{'desc'}; // Get desc from object
$did = $jsonObject->{'did'};// Get id object
mysql_connect("localhost","root",""); // Conect to mysql, first parameter is location, second is mysql username and a third one is a mysql password
#mysql_select_db("findadeal") or die( "Unable to select database"); // Connect to database called test
$query = "UPDATE deal SET dname = {'$name'}, desc={'$desc'} WHERE dealid = {'$did'}";
$add = mysql_query($query);
$num = mysql_num_rows($add);
if($num != 0) {
echo "true";
} else {
echo "false";
}
?>
I believe you are misusing the curly braces. The single quote should go on the outside of them.:
"UPDATE deal SET dname = {'$name'}, desc={'$desc'} WHERE dealid = {'$did'}"
Becomes
"UPDATE deal SET dname = '{$name}', desc='{$desc}' WHERE dealid = '{$did}'"
On a side note, using any mysql_* functions isn't really good security-wise. I would recommend looking into php's mysqli or pdo extensions.
You need to escape reserved words in MySQL like desc with backticks
UPDATE deal
SET dname = {'$name'}, `desc`= {'$desc'} ....
^----^--------------------------here
you need to use mysql_affected_rows() after update not mysql_num_rows
I am getting my variables from form fields using php :
$url=$_POST['url'];
$tags=$_POST['tags'];
$skillArea=$_POST['skill_area'];
$description=$_POST['description'];
$slideshowImageFileName=($_FILES['imageNameSlideshow']['name']);
But when I run my sql insert query, I get an error if one of the variables is empty, so I have taken to write if statements to deal with this to rewrite the query string, but surely, that's not the answer? It seems very messy
if(empty($slideshowImageFileName)){
$query1="INSERT INTO portfolio (item_name,image_path,description,url) VALUES('$itemName','$imageFileName','$description','$url')";
}else{
$query1="INSERT INTO portfolio (item_name,image_path,description,url,slideshow_image_path) VALUES('$itemName','$imageFileName','$description','$url','$slideshowImageFileName')";
}
I suppose you are looking for something like this:
$slideshowImageFileName = (isset($_FILES['imageNameSlideshow']['name']) && !empty($_FILES['imageNameSlideshow']['name'])) ? $_FILES['imageNameSlideshow']['name'] : NULL;
This will check if the name of the slideshowimage is set and not empty. if it is NULL will be assigned to the variable, if its correct the value will be assigned.
You could replace NULL with "" if you want an empty string to be added.
Try to set the value of $slideshowImageFileName to empty string or a single space as your database table will accept, and use the second query always.
if(empty($slideshowImageFileName)){
$slideshowImageFileName = "";
}
$query1="INSERT INTO portfolio (item_name,image_path,description,url,slideshow_image_path) VALUES('$itemName','$imageFileName','$description','$url','$slideshowImageFileName')";
I am agreed with Mr. Ray. But there is another solution apart from that. Probably slideshow_image_path field on the table doesn't allow null. So you may change the attribute by allowing null and it will work.
I'd probably construct a builder if I'm sure I'll get a lot of optional data.
Like this:
$acceptedKeys = array
('item_name',
'image_path',
'description',
'url',
'slideshow_image_path');
$inserts = array();
foreach($_GET as $key => $var) {
if(in_array($key, $acceptedKeys)) {
// clean and validate your keys here!
$inserts[$key] = $var;
}
}
$customKeys = implode(array_keys($inserts), ',');
$customValues = implode($inserts, ',');
$query = "INSERT INTO portfolio ($customKeys) VALUES($customValues)";
There's a few options to this.
Simplest one is to make sure the variables are always set, even if not passed through:
//Set up your database connection as normal, check errors etc.
$db = mysqli_connect($host,$user,$password,$db);
$url = isset($_POST['url']) ? mysqli_real_escape_string($db, $_POST['url']) : "";
$tags= isset($_POST['tags']) ? mysqli_real_escape_string($db, $_POST['tags']) : "";
Escaping data is good practice :) In your INSERT query you'll still need to wrap the values in quotes, or you could do that in the above code as per your preference.
http://uk3.php.net/manual/en/mysqli.construct.php