How to POST a newly defined variable into SQL - beginners PHP - php

The sql column avatar_link isn't updating:
A form submits data and directs to the script (partial) below. The SQL columns: name, comment, email and story_id all insert fine. The image saves to the server with no problem (I didn't include that part of the script to keep things brief). $templink is a newly created variable that should represent the URL of a image uploaded. I'm redefining the variable as $avatar_link and using POST.
$tempLink = "http://www.website.com/avatars/" . $_FILES["file"]["name"];
$page_path = $_POST['page_path'];
$name = $_POST['name'];
$comment = $_POST['comment'];
$email = $_POST['email'];
$storyid = $_POST['storyid'];
$avatar_link = $_POST['$tempLink'];
$con=mysqli_connect
("","","","");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = 'INSERT INTO comments (name, comment, email, storyid, avatar_link, entry_date)';
$sql .= 'VALUES("'.$name.'", "'.$comment.'", "'.$email.'", "'.$storyid.'", "'.$avatar_link.'", now())';
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
I marked the title of this 'beginners PHP' because this question seems very basic (and I can't still figure it out)...if that is not appropriate let me know and I will remove.

$_POST variables come from a submitted form. If you are simply defining a variable and passing it into a statement for insertion into a database, you could eliminate a few steps here, and just do this:
$avatar_link = "http://www.website.com/avatars/" . $_FILES["file"]["name"];
Also, pay attention to #Marc B's comment here. You can learn about parameterizing mysqli statement all over the web, or here on Stack Overflow. What's really best, and what I'd recommend, is learning PDO.

Related

Code won't insert into database

I have the following code that should collect the filled values from a former page and insert them in a MySQLi database. This does not work and I only get a blank page as a result, without any messages. I can't figure out what I'm doing wrong.
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
if(mysqli_connect_errno())
{
echo mysqli_connect_error();
}
$company_name = $_POST['company_name'];
$description = $_POST['description'];
$welcome_text = $_POST['welcome_text'];
$thanks_message = $_POST['thanks_message'];
$image = addslashes (file_get_contents($_FILES['image']['tmp_name']));
$logo = getimagesize($_FILES['image']['tmp_name']);
$image_type = $logo['mime'];
$q = "INSERT INTO project VALUES('','$company_name','$description','$image','$image_type','$welcome_text','$thanks_message')";
$r = mysqli_query($mysqli,$q);
if($r)
{
echo "<h1>Projektet är skapat!</h1><br>
Tryck på knappen nedan för att ta dig till Dashboard.<br><br>
<a href='dashboardadmin.php'><button id='projectbutton'>Dashboard</button></a>";
}
else
{
echo mysqli_errno($mysqli) . ": " . mysqli_error($mysqli) . "\n";
}
?>
Correct syntax of INSERT is:
INSERT INTO table_name (column1,column2,column3,...) VALUES (value1,value2,value3,...);
Please try entering column names before your values first. Also check your $_POST values, whether $_FILES['image'] is available and confirm your mysqli connection.
Edits:
Is the first value (empty one) your primary key? If so, can you omit that bit in your code and try again? (Assuming pid is integer and auto incrementing value.)
INSERT INTO project (project_name, description, image, image_type, welcome_text, thanks_message) VALUES('$company_name','$description','$image','$image_type','$welcome_text',‌​'$thanks_message')
Somehow I don't think this would be Azure specific issue as per your comment.
Can you see any errors in logs etc? Also try echoing the query before you run it and check if you run it directly on your phpmyadmin etc to see if it'd work.
Please also try using echo mysqli_errno($mysqli) . ": " . mysqli_error($mysqli) . "\n";
at if($r){..} else { //here } to see if you get an error.
Latest Update:
$q = "INSERT INTO project (project_name, description, image, image_type, welcome_text, thanks_message) VALUES('".$company_name."','".$description."','".$image."','".$image_type."','".$welcome_text."','".$thanks_message."')";
Try this, because your primary key value is auto incremented.
$q = "INSERT INTO project VALUES('$company_name','$description','$image','$image_type','$welcome_text','$thanks_message')";

SQL database not inserting data?

I am working on a program that takes HTML code made by a WYSIWYG editor and inserting it into a database, then redirecting the user to the completed page, which reads the code off the database. I can manually enter code in phpmyadmin and it works but in PHP code it will not overwrite the entry in the code column for the ID specified. I have provided the PHP code to help you help me. The PHP is not giving me any parse errors. What is incorrect with the following code?
<?php
//POST VARIABLES------------------------------------------------------------------------
//$rawcode = $_POST[ 'editor1' ];
//$code = mysqli_real_escape_string($rawcode);
$code = 'GOOD';
$id = "1";
echo "$code";
//SQL VARIABLES-------------------------------------------------------------------------
$database = mysqli_connect("localhost" , "root" , "password" , "database");
//INSERT QUERY DATA HERE----------------------------------------------------------------
$queryw = "INSERT INTO users (code) VALUES('$code') WHERE ID = '" . $id . "'";
mysqli_query($queryw, $database);
//REDIRECT TO LOGIN PAGE----------------------------------------------------------------
echo "<script type='text/javascript'>\n";
echo "window.location = 'http://url.com/users/" . $id . "/default.htm';\n";
echo "</script>";
?>
Your problem is that mysql INSERT does not support WHERE. Change the query to:
INSERT INTO users (code) VALUES ('$code')
Then to update a record, use
UPDATE users SET code = '$code' WHERE id = $id
Of course, properly prepare the statements.
Additionally, mysqli_query requires the first parameter to be the connection and second to be the string. You have it reversed. See here:
http://php.net/manual/en/mysqli.query.php
It should also be noted that this kind of procedure should be run before the output to the browser. If so, you can just use PHP's header to relocate instead of this js workaround. However, this method will still work as you want. It is just likely to be considered cleaner if queries and relocation is done at the beginning of the script.

Enter variable into sql table Problems

Ok I am having problems insert a variable into a sql table. Heres my code
if (isset ($_GET['comment']))
$commentEntered = $_GET['comment'];
else
$commentEntered = "refuse";
Above I get the variable
Then I try to pass it to the database with the code below
$sql = "insert into $DB_Table (comment) values('$commentEntered');";
$res = mysql_query($sql,$con) or die(mysql_error());
mysql_close($con);
if ($res) {
echo "success";
}else{
echo "faild";
}// end else
My problem is, When I pass a single word it works, But when the text box where comment is received has any spaces in it, It will not insert?
i.e - The user enters Hello - This works
The user enters Hello World - This doesn't work
Any help would be much appreciated!
try
$sql = "INSERT INTO " . $table . " (comment) " .
"VALUES ('" . mysql_real_espace_string($commentEntered) . "')";
Also, dump the var $commentEntered before the "$sql = ..." line just to see what it outputs to the screen.
var_dump($commentEntered);
And another thing, try switching from GET request method to POST and grab the data from $_POST.
try to call:
mysql_query("COMMIT");
before closing the connection.

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.)

Stopping users posting more than once

Before posting my form I am checking the database to see if there are any previous posts from the user. If there are previous posts then the script will kick back a message saying you have already posted.
The problem is that what I am trying to achieve isn't working it all goes wrong after my else statement. It is also probable that there is an sql injection vulnerability too. Can you help??4
<?php
include '../login/dbc.php';
page_protect();
$customerid = $_SESSION['user_id'];
$checkid = "SELECT customerid FROM content WHERE customerid = $customerid";
if ($checkid = $customerid) {echo 'You cannot post any more entries, you have already created one';}
else
$sql="INSERT INTO content (customerid, weburl, title, description) VALUES
('$_POST[customerid]','$_POST[webaddress]','$_POST[pagetitle]','$_POST[pagedescription]')";
if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
?>
To answer the second part of your question: yes, you're very vulnerable to SQL injection:
$sql="INSERT INTO content (customerid, ...) VALUES ('$_POST[customerid]', ...)";
^
This article explains SQL Injection and how to avoid the vulnerability in PHP.
You are missing curly brackets {}:
<?php
if ($checkid == $customerid) {echo 'You cannot post any more entries, you have already created one';}
else
{
$sql="INSERT INTO content (customerid, weburl, title, description) VALUES
('$_POST[customerid]','$_POST[webaddress]','$_POST[pagetitle]','$_POST[pagedescription]')";
if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
}
?>
In addition to the missing curly braces mentioned previously it looks like you're assigning in the if statement, which will cause the statement to always evaluate to true:
if ($checkid = $customerid) {echo 'You cannot post any more entries, you have already created one';}
Should be:
if ($checkid == $customerid) {echo 'You cannot post any more entries, you have already created one';}
Also, $checkid contains an SQL query string. I assume you intend to actually run the query and populate $checkid with something comparable to a $customerid before actually getting to the comparison.
In addition to the SQL injections (man, read a book/tutorial about that before you start!) and the missing braces after the else, you have two errors in there: First, you don't execute the $checkid query, secondly, you only have one = in the if (so you assign the value of $customerid to $checkid.
It is also probable that there is an sql injection vulnerability too.
Why "is possible"? Don't you see that yourself? Don't you write your code in a way that you avoid such issues in the first place?
Re: sql injection - any time you trust data from your users you're vulnerable. Take your INSERT statement and sanitize it.
$sql = sprintf("INSERT INTO content (customerid, weburl, title, description) VALUES ('%d','%s','%s','%s')",
$_POST['customerid'], //forced as digit
mysql_real_escape_string($_POST['webaddress']),
mysql_real_escape_string($_POST['pagetitle']),
mysql_real_escape_string($_POST['pagedescription']) );
Also, you should use apostrophes in your array keys. In double quotes, that'd be:
echo "Post data webpage title is {$_POST['pagetitle']}";
$_SESSION will clear when the browser is closed out. Therefore, I'd suggest using Cookies for a definite way.
I've updated your code as follows:
include '../login/dbc.php';
page_protect();
$customerid = $_COOKIE['user_id'];
$checkid = "SELECT customerid FROM content WHERE customerid = $customerid";
if ($checkid = $customerid) {echo 'You cannot post any more entries, you have already created one';}else{
$sql="INSERT INTO content (customerid, weburl, title, description) VALUES
('$_POST[customerid]','$_POST[webaddress]','$_POST[pagetitle]','$_POST[pagedescription]')";
if (!mysql_query($sql))
die('Error: ' . mysql_error());
else
echo "1 record added";
}
If you are worried about injection add this tidbit prior to your insert query:
foreach($_POST as $key=>$value){
$_POST[$key] = addslashes($value);
}

Categories