Why can't I "INSERT INTO" my table through my php script? - php

I have two different directories on my wampserver, this code works on one, but not on the other, I don't understand why.
PHP
<?php
error_reporting(E_ALL & ~E_NOTICE);
session_start();
$msg = "";
if (!isset($_SESSION['username'])) {
header('Location: login.php');
die();
}
if(isset($_SESSION['username'])) {
if (isset($_POST['submit']))
{
$className = $_POST['className'];
$classColour = $_POST['classColour'];
include_once("connection.php");
$sql = "INSERT INTO class (className, classColour) VALUE ('$className', '$classColour')";
mysqli_query($dbConnection, $sql);
$msg = "New class '" . $className . "' added.";
} else {
$msg = "No class added yet.";
}
}
?>
HTML
<form method="post" action="add_class.php">
<input type="text" name="className" placeholder="Class" />
<input type="text" name="classColour" placeholder="Colour" />
<div><input type="submit" name="submit" value="Add" class="btn butn-orange"/></div>
</form>
This is in the file "add_class.php" and I've tried many different things, putting single quotes (`) around the table columns in the $sql but still, it won't work. I've tried adjusting the names in the table, which had underscores but now have camelCasing, still made no difference. This code works perfectly in another directory, can someone please tell me why this is happening and possibly propose a solution? Thank you in advance.
P.S My connection works because I inserted a new row via phpmyadmin and looped through the database printing every existing "className" and it worked, I just can't insert from the php script.
connection.php
<?php
$dbConnection = mysqli_connect("localhost","root", "", "main");
if(mysqli_connect_errno())
{
echo "Failed to connect" . mysqli_connect_error();
}
?>

When asked if you've had assigned the sessions, you replied I assigned this when the user logs in. Moving forward from that, let's assume the assigned session as one written below:
<?php
error_reporting(E_ALL & ~E_NOTICE);
session_start();
$_SESSION['username'] = "HawqasKaPujaari";
$msg = "";
// this fails, as session is already set.
if (!isset($_SESSION['username'])) {
header('Location: login.php');
die();
}
if(isset($_SESSION['username'])) {
if (isset($_POST['submit']))
{
$className = $_POST['className'];
$classColour = $_POST['classColour'];
include_once("connection.php");
$sql = "INSERT INTO class (className, classColour) VALUES ('$className', '$classColour')";
mysqli_query($dbConnection, $sql);
echo $msg = "New class '" . $className . "' added.";
} else {
$msg = "No class added yet.";
}
}
?>
<form method="post" action="">
<input type="text" name="className" placeholder="Class" />
<input type="text" name="classColour" placeholder="Colour" />
<div><input type="submit" name="submit" value="Add" class="btn butn-orange"/></div>
</form>
Note: The only changes I made were to change the action="" empty and changed VALUE to VALUES in your query.
connection.php:
<?php
$dbConnection = mysqli_connect("localhost","root", "", "main");
if(mysqli_connect_errno())
{
echo "Failed to connect" . mysqli_connect_error();
}
?>
As the above posted code seemed to be correct and was bugging me so I thought of testing it myself by creating the database/tables and it seemed to work properly without any errors. I have posted the relevant pictures below:
Note: Make sure you have the connection.php file in the same
directory as the add_class.php.

Related

Unable to update database row in PHP with $_POST variable

I want it so that when the user types into the textarea/input and clicks save changes, the information they input has been added and saved into the database. Below is my code:
$name = $_SESSION['u_name'];
$uid = $_SESSION['u_uid'];
$id = $_SESSION['u_id'];
$con = mysqli_connect("localhost", "root", "pass123", "db_name");
if ($con->connect_error) {
die("Connection failed: " . $conn->connect_error);
echo "<script type='text/javascript'>alert('connection failed. try again');</script>";
}
$remind1 = $_POST['remind1'];
$remind2 = $_POST['remind2'];
$remind3 = $_POST['remind3'];
$remind4 = $_POST['remind4'];
$remind5 = $_POST['remind5'];
if (isset($_POST['updBtn'])){
$sql = "UPDATE reminders SET remindone='$remind1' WHERE username='$uid'";
if ($con->query($sql) === TRUE) {
echo "<script type='text/javascript'>alert('Updated successfully');</script>";
}else{
echo "<script type='text/javascript'>alert('error while updating. try again');</script>";
}
}
Below is the corresponding HTML:
<form action="body.php" method="post">
<input type="submit" class="sideBtn" value="Save Changes" name="updBtn"><br>
<input type="text" class="event" name="remind1"><br>
<input type="text" class="event" name="remind2"><br>
<input type="text" class="event" name="remind3"><br>
<textarea class="event" name="remind4"></textarea><br>
<textarea class="event" name="remind5"></textarea><br>
</form>
Ideally what would happen, is that whatever the user types into the textarea/input is updated in the database, then they can access and later tweak the text if they need to.
I have been able to pinpoint that my problem is somewhere along the $_POST variables in my PHP as, if I were to substitute the aforementioned variable with a string as such:
$sql = "UPDATE reminders SET remindone='hello' WHERE username='$uid'";
...it works perfectly. But with when using the POST variable, it does not work.
How can I fix this mistake of mine and make it so that the user is able to post text into the database? Is the $_POST variable required here or is there another method to achieve this?

Form is not posting to MySQL database

I am trying to send data from a textfield to my database. When I run the code I get no errors. But the code isnt posting the data to the database. I cant see whats wrong, can someone look what is wrong?
index.php
<?php
session_start();
?>
<html>
<form name="reaction" method="post" action="./send/send1.php">
<input type="text" class="form-control" id="data_1" name="data_1" placeholder="Data 1" />
<button name="send">Send</button>
</form>
</html>
send1.php
<?php
session_start();
?>
<html>
<body>
<table>
<?php
$correct = true;
$data_1 = $_POST['data_1'] ;
?>
</table>
<?php
if($correct){
$db = new PDO('mysql:host=localhost;dbname=database', 'root', '');
$query = "UPDATE table SET data_1=" . $data_1 . " WHERE id='" . $_SESSION['ID'] ."'";
$stmt = $db->prepare($query);
$stmt->execute(array($adres_1));
echo "<br /><br />Success.<br />\n";
} else {
echo "<br /><br />Error.<br />\n";
}
?>
</body>
</html>
a) your script needs more error handling.
Before accessing $_POST['data_1'], you should test its existence, e.g. via isset().
Your database code doesn't have any error handling, too. Either set the error mode to PDO::ERRMODE_EXCEPTION or (/and) make sure you test each and every return value of the PDO::* methods.
$db = new PDO('mysql:host=localhost;dbname=database', 'root', '');
$query = "UPDATE table SET data_1=" . $data_1 . " WHERE id='" . $_SESSION['ID'] ."'";
$stmt = $db->prepare($query);
if ( !$stmt ) {
yourErrorHandler('could not prepare statement', $db->error);
}
else if ( !$stmt->execute(array($adres_1)) ) {
yourErrorHandler('could execute statement', $stmt->error);
}
else if ( 1>$stmt->rowCount() ) {
// no record has been updates
}
else {
// at least one record has been updated
}
b) $stmt->execute(array($adres_1)); What is $adres_1? It's not anywhere else in that code.
c) Your code is prone to sql injections. You can fix that e.g. by using prepared statements + parameters.
The whole code looks like small parts of other scripts have been copy&pasted without understanding what those snippets do.
Are you using autocommit? maybe your db changes are being rolled back. Try adding an extra COMMIT SQL statement.
You have to submit your code. Then only the values are send to the php file by the POST method.
index.php
<?php
session_start();
?>
<html>
<form name="reaction" method="post" action="./send/send1.php">
<input type="text" class="form-control" id="data_1" name="data_1" placeholder="Data 1" />
<input type="submit" name="send">Send</button>
</form>
</html>
send1.php
<?php
session_start();
?>
<html>
<body>
<table>
<?php
$correct = true;
if ($_POST['send']) {
$data_1 = $_POST['data_1'] ;
}
?>
</table>
<?php
if($correct){
$db = new PDO('mysql:host=localhost;dbname=database', 'root', '');
$query = "UPDATE table SET data_1=" . $data_1 . " WHERE id='" . $_SESSION['ID'] ."'";
$stmt = $db->prepare($query);
$stmt->execute(array($adres_1));
echo "<br /><br />Success.<br />\n";
} else {
echo "<br /><br />Error.<br />\n";
}
?>
</body>
</html>

PHP and SQL not Posting

My PHP code to POST to my SQL on Godaddy's hosting is not working for some reason.. I added debug statements but I'm just not sure why it's not working. It's driving me crazy.
Here's my file named "homepage.php":
<?php
if (isset($_POST['submitted'])) {
include('mysql_connection.php');
$entry = $_POST['entry'];
$sql = "INSERT INTO posts (typed) VALUES ('$entry')";
if (!mysqli_query($dbcon, $sql)) {
die('Error inserting text.');
}
$newentry = "One entry added to the database.";
}
?>
HTML
<html>
<head> </head>
<body>
<center>
<form method="post" action="homepage.php">
<input type="hidden" name="submitted" value="true" />
<input type="text" name="entry" maxlength="200" />
<br></br>
<input type="submit" value="insert" />
</form>
</center>
<?php echo $newentry?>
</body>
</html>
And my database is named "subpost-db" with the table "posts" and a column named "typed" with VARCHAR values.
My SQL connection file is named "mysql-connection.php" and here's the code:
<?php
DEFINE ('DB_USER', 'xxxxxxxxxx');
DEFINE ('DB_PSWD', 'xxxxxxxxxx');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'subpost-db');
$dbcon = mysqli_connect(DB_HOST, DB_USER, DB_PSWD, DB_NAME);
if (!$dbcon) {
die('Error connecting to the requested database. ');
}
?>
By the way, when I go to mysql-connection.php on my website, the debug message does not pop up.
When I click "insert" after typing something on my form, it reloads homepage.php, where my form is, and only displays the text that says "Error inserting text." but I'm not sure what the problem is.
You are getting an error from your query so add the correct reporting to the test after the code that issues the query to the database and it will tell you what is wrong.
<?php
// from Fred-ii- comment
error_reporting(E_ALL);
ini_set('display_errors', 1);
if (isset($_POST['submitted'])) {
include('mysql_connection.php');
$entry = $_POST['entry'];
$sql = "INSERT INTO posts (typed) VALUES ('$entry')";
if (!mysqli_query($dbcon, $sql)) {
die('Error inserting text. ' . mysqli_error($dbcon) ); //<-- changed line
}
$newentry = "One entry added to the database.";
}
?>

Delete Button in PHP isn't Working

I'm trying to add a php button on to my site, however it doesn't seem to be working.
The delete php script is;
if(isset($_POST["delete"])) {
$delquery = "DELETE FROM emails WHERE ID=$_POST["delete"]";
mysqli_query($connection, $delquery);
}
And the form looks like which is on the same file;
<form action="email-response.php" method="post">
<input type="hidden" name="hidden" value="<?php echo $row['ID']; ?>">
<input type="submit" name="delete" value="delete">
</form>
However whenever I clicked the delete button nothing is happening.
In relation to the reply saying that my $connection function is wrong, here is the function however its working as it is fetching my information for my posts.
define("DB_SERVER", "myservername");
define("DB_USER", "myusername"); //username
define("DB_PASS", "mypassword"); //password
define("DB_NAME", "mydbname"); // database name
$connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
if(mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
} else {
echo "connected";
}
The element you wish to delete is named hidden and not delete.
That is what your submit button is named as (delete).
Change your query to this:
if(isset($_POST["delete"]) && !empty($_POST["hidden"])){
$id = mysqli_real_escape_string($connection, $_POST["hidden"]);
}
$delquery = "DELETE FROM emails WHERE ID='$id'";
mysqli_query($connection, $delquery) or die(mysqli_error($connection));
if(mysqli_affected_rows($connection)){
echo "It was really successful.";
}
isset($_POST["delete"]) is to check if the submit button was clicked.
Using mysqli_affected_rows() will show you if your query was truly successful.
This is a function I've grown to use more often.
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);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
Sidenote: Using your present method, leaves you open to SQL injection.
Use mysqli with prepared statements, or PDO with prepared statements, they're much safer.
Your connection is good.
Here is the solution which will work and is simple:
Your form:
<form action="#" method="post">
<input type="hidden" name="to_delete" value="<?php echo $row['ID']; ?>">
<input type="submit" name="delete" value="delete">
</form>
Your delete script:
if(isset($_POST["delete"]))
{
$delquery = "DELETE FROM user WHERE ID=".$_POST['to_delete']."";
mysqli_query($connection, $delquery);
}

MySql search script writes an unkown error

This is my second post on stackoverflow, and i hope u will help me resolve this one too.
When i run this script it says "Undefined variable: search_name".i don't know what is problem.
Hope u are going to help.
Ty :D .
<?php
$con=mysqli_connect("localhost","root","","test");
if (mysqli_connect_errno())
{
echo "Error" .mysqli_connect_error();
}
if(isset($_POST['go']))
{
$search_name = mysqli_real_escape_string($con, $_POST['form_name']);
}
$select_name=mysqli_query($con,"SELECT * FROM test_mysql WHERE name='$search_name' ");
while($row=mysqli_fetch_array($select_name))
{
$ime=$row['name'];
$prezime=$row['lastname'];
$id_number=$row['id'];
echo $id_number." . ".$ime. " ".$prezime."<br>";
}
?>
<form action="" methom="post">
Name: <input type="text" name="form_name"/>
<input type="submit" value="send" name="go"/>
</form>
You need to move your query inside the isset() of your submit button, otherwise the code will be executed everytime the page loads causing the error.
if(isset($_POST['go']))
{
$search_name = mysqli_real_escape_string($con, $_POST['form_name']);
$select_name=mysqli_query($con,"SELECT * FROM test_mysql WHERE name='$search_name' ");
while($row=mysqli_fetch_array($select_name))
{
$ime=$row['name'];
$prezime=$row['lastname'];
$id_number=$row['id'];
echo $id_number." . ".$ime. " ".$prezime."<br>";
}
}
?>
<form action="" methom="post">
Name: <input type="text" name="form_name"/>
<input type="submit" value="send" name="go"/>
Simply, just make sure the form is submitted before building the query, you already do that but not to all the parts of the code
if(isset($_POST['go']))
{
$search_name = mysqli_real_escape_string($con, $_POST['form_name']);
$select_name=mysqli_query($con,"SELECT * FROM test_mysql WHERE name='$search_name' ");
while($row=mysqli_fetch_array($select_name))
{
$ime=$row['name'];
$prezime=$row['lastname'];
$id_number=$row['id'];
echo $id_number." . ".$ime. " ".$prezime."<br>";
}
}
This should solve it.

Categories