So I'am trying to add Php code to the database it works when I insert it in the database. But when I go to the browser the Php code I added was commented
code:
$insert =
'</div>
<br><br><br>
<div class="posts-container">
<img src="'.$img.'" class="profpic"/>
<div class="editB-cont">
<img src="img/editB.png" class="editB"/>
</div>
<h1>'.$sender.'</h1>
<hr class="solid">
<p class="post-text-container">'.$post.'</p>
<br><br>
<img src="'."attatch/".$newfilename.'" class="attach"/>
<br><br>
<form action="post-comment" method="post">
<input type="hidden" name="parent-id" value="<?= echo $postId; ?>">
<input type="text" name="comment-text" placeholder="Comment...">
<input type="submit" value="Post" name="submit">
</form>
<br>
<div class="coments">
<?= include("get-comment.php"); ?>
</div><br>
</div><br><br>
';
$sql = "INSERT INTO posts (sender, post, sender_id, image_attach, sender_img) VALUES ('$sender', '$insert', $id, 'attatch/$newfilename', '$img')";
if (mysqli_query($conn, $sql)) {
header("Location: view-profile?id=$id");
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
Is there any way to fix this?
Like Dharman said, $insert should be divided, so assign your include to a variable and then create $insert like so:
'first part until div class=comments' . $includeVariable . 'second part';
Regarding the sql injection, just google php prepared statements, or check this w3schools article https://www.w3schools.com/php/php_mysql_prepared_statements.asp
EDIT
in get_comment.php
$comment = 'just a test';
return $comment;
then
$includeVariable = include('get_comment.php');
$insert = 'first part' . $includeVariable . 'second part';
EDIT 2
You could try using eval() to display $insert or that commented part of it, HOWEVER as php manual states:
Caution The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.
This leads to another issue, probably the most important one: storing blocks of code like that in a database is a sign of a seriously bad design, you should think how to avoid it and rewrite you code rather than try to make it work
EDIT 3
Your PDO is wrong, in $link->prepare() number of database columns you insert into and number of inserted values must be the same, for example, I insert two values into two columns:
INSERT INTO user(name, age) VALUES (:name, :age)
which is same as
INSERT INTO user(name, age) VALUES (?, ?)
then you bind parameters
$statement->bind_param('si', $name, $age)
where 'si' are parameters types: (s)tring and (i)nteger, check https://www.php.net/manual/en/mysqli-stmt.bind-param.php for details
then assing values to you variables
$name = 'John';
$age = 44;
finally execute
$statement->execute();
Related
I made a simple form with two variables which should be sent to database after SUBMITing them. However even thought there is no bug reports, the database is still empty after submit. Where Can I look for mistake?
I already tried multiple ' or " or '", none of these worked. I can with no problem SELECT data from fdatabase so the connection is established.
$total = $_POST['kwota'];
$way = $_POST['sposob'];
echo $total . "<BR>" . $way;
$sql = "INSERT INTO payments (Total, Way) VALUES ('$kwota', '$sposob');";
mysqli_query($conn, $sql);
header("Location: ../index.php?Payment=success");
<form action="includes/Platnosc.inc.php" method="POST">
<input type="text" name="kwota" placeholder="kwota"><br>
<input type="text" name="sposob" placeholder="sposób"><br>
<button type="submit" name="submit">Dodaj płatność</button>
</form>
You are inserting $_POST array indexes as php variables. Change your query to this
$sql = "INSERT INTO payments (Total, Way) VALUES ('$total', '$way')";
However, I suggest you to use prepared statements to prevent from sql injections
I want the data inputed into the form by the user to be submitted to a database. But for some reason my code isn't working?
<form action="newpostsubmit.php" method="post">
<h2 class="form-signin-heading">New Post (beta)</h2>
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" name="title" id="title">
</div>
<br>
<div class="form-group">
<label for="post">Post</label>
<textarea class="form-control" rows="5" name="post" id="post"></textarea>
</div>
<br>
<input type="submit">
</form>
PHP submit
<?php
//Connecting to sql db.
$connect = mysqli_connect("localhost","root","pwd","db");
//Sending form data to sql db.
mysqli_query($connect,"INSERT INTO posts (title, post)
VALUES ('$_POST[title]', '$_POST[post]')";
?>
First, your $_POST variables are incorrect as you're forgetting to quote the item like $_POST['title'].
Second, you really should use prepared statements. They'll make your code cleaner and have the added benefit of protecting you against SQL Injection Attacks..
You should also perform minimal error checking of your connection and your queries, it is likely that you're missing some information that will help you to be successful. The errors are already in your error log, but you can make them echo out to the screen.
//Connecting to sql db.
$connect = mysqli_connect("localhost","root","pwd","db");
if (!$connect) {
echo "Connection failed: ". mysqli_connect_error();
exit();
}
//Sending form data to sql db.
$stmt = mysqli_prepare($connect, "INSERT INTO `posts` (`title`, `post`) VALUES (?,?)");
mysqli_stmt_bind_param($stmt, 'ss', $_POST['title'], $_POST['post'] );
// execute prepared statement
mysqli_stmt_execute($stmt);
// was there a problem?
if(mysqli_stmt_error($stmt)) {
echo "There was an error performing the query, " . mysqli_stmt_error($stmt);
}
There is a a lot going on here, but most notable is the prepare() where you use placeholders for your variables (?) and mysqli_stmt_bind_param() to bind your variables, as strings (s for each item) to the query.
Finally, check if there are any errors and echo those back to the screen with mysqli_stmt_error()
NOTE: Make sure to handle errors gracefully for your users, never displaying the actual problems to them which exposes your site to attacks. Echoing the information to the screen, as is being done here, is fine during the development stage.
You need to clean your POSTed variables to prevent SQL injections and other errors, and then quote them properly (as strings) on inserting them into the db.
$cleanTitle = mysqli_real_escape_string($connect,$_POST['title'];
$cleanPost = mysqli_real_escape_string($connect,$_POST['post'];
$sql = "INSERT INTO posts (title, post) VALUES ('$cleanTitle', '$cleanPost')";
$insert = mysqli_query($connect,$sql);
if(!$insert){
echo 'ERROR :'.mysqli_error($connect);
}
mysqli_query($connect,"INSERT INTO posts (title, post)
VALUES ('".$_POST[title]."', '".$_POST[post]."')";
query should be like this. Hope this helps.
I am trying to build an "admin" section of my website. One where I can update customer status on work orders (or tickets if you prefer the term). I have it where I can input an int in a text field and hit submit to DELETE, but I cannot get my addRow function to work. It is not causing an error, which makes me believe that I am not passing my variables correctly.
Here are the forms on admin.php:
<form name="newRow" METHOD="post" ACTION="q.php">
Status of New Entry: <input type="text" value="Open" name="newStatus" /><br>
Type of Maintenance being completed: <input type="text" value="Software Maintenance" name="maintType" /><br>
<input type="submit" value="Add" name="newEntry" />
</form>
<form name="delRow" METHOD="post" ACTION="q.php">
<input type="text" name="deleteID" />
<input type="submit" value="Delete" name="delEntry"/>
</form>
As for my q.php, here is what I have after I connect to my db (which again, I have no problems using the delEntry/delRow section, so I can't see how a connection/mysqli initialization problem would be the issue:
//prepare statements
$addData = $conn->prepare("INSERT INTO $tname (status, mainttype) VALUES (?, ?)");
$addData->bind_param("s,s", $newStatus, $maintType);
$delData = $conn->prepare("DELETE FROM $tname WHERE id=?");
$delData->bind_param("i", $deleteID);
//end prepared statements
//if New Entry Button is pressed
$newStatus = isset($_POST['newStatus'])
? $_POST['newStatus']
: '';
$maintType = isset($_POST['maintType'])
? $_POST['maintType']
: '';
$addData->execute();
if ( false===$addData ) {
die('prepare() failed: ' . htmlspecialchars($mysqli->error));
}
else{
printf("rows inserted: %d\n", $addData->affected_rows);
}
//if Del Entry Button is pressed
if ( isset( $_POST['delEntry'] ) ) {
$deleteID = $_POST['deleteID'];
$delData->execute();
}
$addData->close();
$delData->close();
$conn->close();
?>
my columns are matching according to phpMyAdmin:
$addData = $conn->prepare("INSERT INTO $tname (status, mainttype) VALUES (?, ?)");
status and mainttype (yes 2 t). my ID (primary) is an auto_incriment so I left it out because I don't want to cause any key duplicate errors by accident. It's auto_incriment has been tested and seems to be working fine.
Too make it more fun, I added an echo $newStatus; after my prepared statement execution, and it comes back with the correct value. I appear to be having a problem with the addition of the new row. Still no error being generated.
printf("rows inserted: %d\n", $addData->affected_rows);
returns with 0 rows affected as well.
Simple comma issue. On:
$addData->bind_param("ss", $newStatus, $maintType);
I had it listed as:
$addData->bind_param("s,s", $newStatus, $maintType);
I just want to transfer the information from a text form into a database, but the value doesn't appear in the database properly. Here's what I have:
HTML code, for the form:
<form method="post" action="process.php">
<input type="text" maxlength="150" name="textbox">
<input type="submit" name="submit">
</form>
process.php
<?php
$con=mysqli_connect($host, $username, $password, $database);
$sql = mysqli_query($con,"INSERT INTO notes (User, Note)
VALUES ('test', '$_POST [textbox]')");
// I also tried writing $_POST ['textbox'] instead; didn't make a difference.
?>
However, the output in the database is as follows:
User: test
Note: Array [textbox]
How would I be able to correct the value in the Note column (i-e to make it the value entered in the form)?
First off...you had a space between $_POST and ['textbox'];
it shoulda just been $_POST['textbox']...
But also you need to sanitize the data first so...
Try this
$input = mysqli_real_escape_string($_POST['textbox']);
$sql = mysqli_query($con,"INSERT INTO notes (User, Note)
VALUES ('test', '$input')");
But really you should use PDO instead of the deprecated mysql_* functions...
Google PDO, and learn to do prepared statements.
Here it is with PDO...
$conn = new PDO("mysql:host=$host;dbname=$database",$username,$password);
$user = 'Test';
$note = $_POST['textbox'];
$sql = "INSERT INTO notes (User, Note) VALUES (:user,:note)";
$q = $conn->prepare($sql);
$q->execute(array(':user'=>$user,
':note'=>$note));
EDIT...
I also noticed your inputs aren't closed, there should be a / at the end of each...
<form method="post" action="process.php">
<input type="text" maxlength="150" name="textbox" />
<input type="submit" name="submit" />
</form>
You have a space between $_POST and [textbox]. $_POST is an array. Hence, Array [textbox], ie: ArraySPACE[textbox]
You should remove the space, then look into using prepared statements. You should not use user submitted data directly without sanitizing it first.
$sql = mysqli_query($con,"INSERT INTO notes (User, Note)
VALUES ('test', '{$_POST['textbox']}')");
I am trying to make a form using html and php to update mysql database. the database updates (autoincrements) the keys, but it does not add any of the strings to the values. i have searched people with similar problems but because their codes are different than mine I cannot understand it (i am a noob with php and mysql) I think my problem is in the way that i use the html to get the values but I could be wrong
<form action=submitform.php method=GET>
Name:<input type="text" name="cuName" size=20 maxlength=20><br>
Password:<input type="password" name="password" size=20 maxlength=45><br>
Account:<input type="text" name="account" size=20 maxlength=45><br>
Phone:<input type="tel" name="phone" size=10 maxlength=10><br>
Email:<input type="text" name="email" size=20 maxlength=45><br>
<input type=submit>
</form>
and my php is
<?php
mysql_connect(localhost, myUsername, "myPassword");
mysql_select_db(myDatabaseName);
mysql_query("INSERT INTO Customer (cuName, password,
account, phone, email)
Values('$cuName', '$password', '$account',
'$phone', '$email')");
echo $cuName ." thank you for reserving!";
print ($cuName);
?>
thanks in advance for any help
Your code is relying on REGISTER_GLOBALS to be turned on; it is usually turned off for security reasons.
You should replace $cuName with $_GET['cuName'] to get the values that are sent from the form.
Additionally, you should escape any value that is going to the database otherwise you may be exposing yourself to an SQL injection vulnerability.
Cleaning up your code for both these scenarios, results in something like this:
<?php
if (!mysql_connect(localhost, myUsername, "myPassword")) {
print 'There was an error connecting to the database'.mysql_error();
exit();
}
if (!mysql_select_db(myDatabaseName)) {
print 'Could not select db. The error was: '.mysql_error();
exit();
}
$query = "INSERT INTO Customer (`cuName`, `password`, `account`,`phone`,`email`)";
$query .= "VALUES (";
$query .= "'".mysql_real_escape_string($_GET['cuName'])."','";
$query .= mysql_real_escape_string($_GET['password'])."','";
$query .= mysql_real_escape_string($_GET['phone'])."','";
$query .= mysql_real_escape_string($_GET['email'])."'";
if (!mysql_query($query)) {
print 'There was an error inserting '.$query.'. Error was '.mysql_error();
} else {
echo $_GET['cuName']." thank you for reserving!";
}
print $_GET['cuName'];
?>
I also added some error checking. You should always check results of functions that rely on external systems (such as databases) because you never know what is the status of the database (it could be down, not working, etc.) So you should always check and print any error messages.
You don't define any of your GET values anywhere. $cuName, etc are not defined.
Each value needs to be associated to the $_GET. IE,
$cuName = $_GET['cuName']
But you also need to make sure you don't insert data that hasn't been cleaned to prevent SQL injection. An example of this is:
$cuName = mysql_real_escape_string($_GET['cuName']);
So, try this:
<?php
mysql_connect(localhost, myUsername, "myPassword");
mysql_select_db(myDatabaseName);
//Define Variables
$cuName = mysql_real_escape_string($_GET['cuName']);
$password = mysql_real_escape_string($_GET['password']);
$account = mysql_real_escape_string($_GET['account']);
$phone = mysql_real_escape_string($_GET['phone']);
$email = mysql_real_escape_string($_GET['email']);
mysql_query("INSERT INTO Customer (cuName, password,
account, phone, email)
Values('$cuName', '$password', '$account',
'$phone', '$email')") or die (mysql_error());
echo $cuName ." thank you for reserving!";
print ($cuName);
?>
Better to use:
$cuname = $_GET['cuname'];
like this....
Because your form method is on "GET",and my advise is to POST data than GET.