MED Schularberit - php

I have made a form which collets data form user and sendes them to the database,I wanted to add an addtional option to delete records that user choose.Im having trouble doing that and I would be very thankful i you cound help me.I am new in PHP so sorry that maybe I have done some "stupid" mistakes
The error I get:Notice: Undefined index: name in /var/customers/webs/harlac17/med3/shopping/delete.php on line 27
Code list.php Here are the POST data sent to Database and than showed in Web
<!DOCTYPE html>
<html>
<head>
<title>Shoppinglist</title>
<meta charset="utf-8">
</head>
<body>
<header>
<h1>Shoppinglist</h1>
Neue Produkt anlegen
</header>
<br>
<?php
error_reporting(0);
$database="****";
$username="****";
$password="****";
//Create a database connection with PDO(PHP Data Objects)
$connection=new PDO("mysql:host=localhost;dbname={$database}",$username,$password);
$name = $_POST['name'];
$description = $_POST['description'];
$image_url = $_POST['image_url'];
$count = $_POST['count'];
$sql = "INSERT INTO items(name,description,image_url,count) VALUES (?, ?, ?, ?)";
$statement=$connection->prepare($sql);
$statement->execute([$name, $description, $image_url, $count]);
$items=$connection->query("SELECT * FROM items");
while ($row = $items->fetch()) {
echo "<article>"." ".
"<button>"." ".
"<p>✖</p>"." ".
"</button>"." ".
"<h1>"." ".
$row['name']." ".
"</h1>"." ".
"<br>"." ".
"</p>"." ".
$row["description"]." ".
"</p>"." ".
"<br>"." ".
"<p>"." ".
"<img src='" . $row['image_url'] . "'>"." ".
"</p>"." ".
"<br>"." ".
"<p>"." ".
"Menge:" .$row['count']." ".
"</p>"." ".
"<br>"." ".
""." ".
"</article>"."".
"<a href='delete.php?id=". $row['name']. "'>DELETE</a>";
}
?>
</body>
Code delete.php
<?php
$database="";
$username="";
$password="";
//Create a database connection with PDO(PHP Data Objects)
$connection=new PDO("mysql:host=localhost;dbname={$database}",$username,$password);
$name = $_POST['name'];
$sql = "DELETE FROM items WHERE name='".$name."'";
$statement=$connection->prepare($sql);
$statement->execute();
?>
new.php Form with POST data
<!DOCTYPE html>
<html>
<head>
<title>Einkafsliste Formular</title>
</head>
<body>
<header>
<h1>        Produkte anlegen</h1>
</header>
<div class="form">
<form action="list.php" method="POST">
<label>Name:</label>
<br>
<input type="text" name="name" placeholder="Lebensmittelname" >
<br>
<label>Description:</label>
<br>
<input type="text" name="description" placeholder="Das ist..." >
<br>
<label>Bild URL:</label>
<br>
<input type="text" name="image_url" placeholder="Das URL von Lebensmittelbild" >
<br>
<label>Count:</label>
<br>
<input type="text" name="count" placeholder="Wie viel?" >
<br>
<input type="submit" name="submit" id="submit">
</form>
</div>
</body>
</html>

Firstly, don't include your SQL passwords on Stack Overflow :D
You will want to take a look at a couple of things here, note the try/catch (exceptions) usage, this is a good way of catching errors using PDO to show you where you are going wrong (read: https://www.php.net/manual/en/language.exceptions.php)
Also note how my sql string doesn't have the variable directly entered. This is bad practice and can leave your application open to sql injection vulnerabilities. Always escape your SQL commands using PDO->execute(). (read: https://doc.bccnsoft.com/docs/php-docs-7-en/pdostatement.execute.html)
For the 'Undefined index: name' error, you want to check if $_POST['name'] actually exists before you use it.
if (!#$_POST['name']) {
echo 'Missing POST: name';
die();
}
$name = $_POST['name'];
$username = "";
$password = "";
$database_name = "";
$database_host = "localhost";
$port = 3306;
try {
$con = new PDO("mysql:host=$database_host;port=$port;dbname=$database_name;charset=utf8mb4", $username, $password);
} catch (Exception $e) {
echo($e->getMessage());
die();
}
$statement = $con->prepare("DELETE FROM items WHERE name = :name");
try {
$statement->execute([
':name' => $name,
]);
} catch (PDOException $e) {
echo($e->getMessage());
die();
}

I believe the problem is with this line in delete.php, where PHP is unable to convert the PDO object to a string:
echo ("$connection");
Try removing it and test if it works fine.

Related

Insert a random image in mysql database using php

I am trying to make a CRUD application. on the Create page I have to have three fields (title, text, category). the problem is that I have to make a method / function in PHP or JS that chooses a random picture from the "images" file and automatically loads it in the database along with the other 3 fields. then it has to appear on the admin.php page together with the other 3 fields.
Images have almost the same name except the last digit which differs (1-2-3)
I have no idea how to make this method/function.
my create.php page
// Include config file
require_once "config.php";
// Define variables and initialize with empty values
$title = $text = $category = "";
$title_err = $text_err = $category_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate title
$input_title = trim($_POST["title"]);
if(empty($input_title)){
$title_err = "Please enter a title.";
} else{
$title = $input_title;
}
// Validate text
$input_text = trim($_POST["text"]);
if(empty($input_text)){
$text_err = "Please enter an text.";
} else{
$text = $input_text;
}
// Validate category
$input_category = trim($_POST["category"]);
if(empty($input_category)){
$category_err = "Please enter the category.";
} else{
$category = $input_category;
}
// Check input errors before inserting in database
if(empty($title_err) && empty($text_err) && empty($category_err)){
// Prepare an insert statement
$sql = "INSERT INTO informatii (title, text, category) VALUES (?, ?, ?)";
if($stmt = $mysqli->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bind_param("sss", $param_title, $param_text, $param_category, );
// Set parameters
$param_title = $title;
$param_text = $text;
$param_category = $category;
// Attempt to execute the prepared statement
if($stmt->execute()){
// Records created successfully. Redirect to landing page
header("location: admin.php");
exit();
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
$stmt->close();
}
}
?>
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Create Record</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<style>
.wrapper {
width: 600px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<h2 class="mt-5">Create Record</h2>
<p>Please fill this form and submit to add employee record to the database.</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group">
<label>title</label>
<input type="text" name="title"
class="form-control <?php echo (!empty($title_err)) ? 'is-invalid' : ''; ?>"
value="<?php echo $title; ?>">
<span class="invalid-feedback"><?php echo $title_err;?></span>
</div>
<div class="form-group">
<label>Text</label>
<textarea name="text"
class="form-control <?php echo (!empty($text_err)) ? 'is-invalid' : ''; ?>"><?php echo $text; ?></textarea>
<span class="invalid-feedback"><?php echo $text_err;?></span>
</div>
<div class="form-group">
<label>Category</label>
<textarea name="category"
class="form-control <?php echo (!empty($category_err)) ? 'is-invalid' : ''; ?>"><?php echo $category; ?></textarea>
<span class="invalid-feedback"><?php echo $category_err;?></span>
</div>
<input type="submit" class="btn btn-primary" value="Submit">
Cancel
</form>
</div>
</div>
</div>
</div>
</body>
</html>
this should get you in the right direction (saving the image src is enough), you of course will have to adapt the path to your image folder, and image name
$nr_images = 3;
$random_nr_index = random_int(1,$nr_images);
$random_image_src = '/images/image-'.$random_nr_index.'.jpg';
To do it you need more than one step creating:
A simple html page to post 3 fields value and the image
A php file that receive the post fields and the image and save into mysql
A simple admin.PHP page that shows 3 fields and image
if you already have the images on the server please specify it in a comment
STEP 1:
<html>
<body>
<form method="POST" action="post.php">
f1:<input type="text" name="field1"><br>
f2:<input type="text" name="field2"><br>
f3:<input type="text" name="field3"><br>
im:<input type="file" name="image"><br>
<input type="submit" value="Save">
</form>
</body>
</html>
STEP 2: post.php
<?php
$f1=$_POST["field1"];
$f2=$_POST["field2"];
$f3=$_POST["field3"];
$im=$_POST["image"];
if ($f1 == "" || $f2 == "" || $f3 == "" ){
die("Errors: fields can't be empty! Go back check the fields and try Again");
}
//Saving image on Server's file system if any image
if(isset($_POST["image"])) {
//Saving image with no checking nothing: filetype, mime , extention (it may be very dangerous in a real server exposed to the public)
$where_save = "images/";
$im_name = basename($_FILES["image"]["name"]);
$tmp_name = $_FILES["image"]["tmp_name"];
move_uploaded_file ( $tmp_name , $where_save.$im_name );
}
$h = "localhost";
$u = "username";
$p = "password";
$db = "yourDB";
// Creating connection to mysql server
$conn = mysqli_connect($h, $u, $p, $db);
// Checking connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// WARNINGS ------------------------------------------------
// I do not care about security , please pay attention to it .
// use some mysql_escape_string , or real_mysql_escape_string
// could mitigate the violence of some sqlinjection attack
$sql = "INSERT INTO yourtable (field1, field2, field3,im_name)
VALUES ('$f1', '$f2', '$f3',$im_name)";
//executing mysql query to save data into it
if (!mysqli_query($conn, $sql)) {
die("Error: " . $sql . "<br>" . mysqli_error($conn));
}
//closing connection
mysqli_close($conn);
//Now we can redirect the user to admin.php where we show data
header("Location: admin.php");
?>
STEP 3:
<?php
$where_are_images="images/";
$h = "localhost";
$u = "username";
$p = "password";
$db = "yourDB";
// Again creating connection to mysql server
$conn = mysqli_connect($h, $u, $p, $db);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
//now we want to read the data from mysql
$sql = "SELECT * FROM yourtable LIMIT 1"; //just limit to the first record
$result = mysqli_query($conn, $sql);
?>
<html>
<body>
<h2>Admin page</h2>
<em> hey every one can see top secret data here , Needs soma care about security!</em>
<?php while($d = mysqli_fetch_assoc($result)){ // LOOPING ?>
<br>
f1:<?= $d["field1"] ?><br>
f2:<?= $d["field2"] ?><br>
f3:<?= $d["field3"] ?><br>
<img src="<?=$where_are_images.$d['im_name']?>">
<br>
<br>
<?php } ?>
</body>
</html>
<php? // CLOSING AND FREE RESOURCES
mysqli_free_result($result);
mysqli_close($conn); ?>
Now you have all you need . Have fun editing it with random images part ...
I hope there are no error (i have not tested it)

mysqli insertion query neither insert records nor shows the location of error

I'm trying to execute an sql query that insert a record into a database on WAMP server, but when after pressing the submit button on form, that calls the php code, nothing happens. it just shows the message "Record insertion failed" i provided in the script. after trying and searching for a period of time, i'm unable to find WHERE IS THE ERROR IN QUERY. the code is give below:
<?php
$server="localhost";
$user="root";
$password="";
$database="dbname";
$con = mysqli_connect($server,$user,$password,$database);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//variables getting values from HTML form
if(isset($_POST['Submit-Personal'])){
$name = $_POST['name'];
$cnic = $_POST['cnic'];
$date = $_POST['booking-date'];
$ocassion = $_POST['ocassion'];
$address = $_POST['address'];
$phoneno = $_POST['phone-no'];
$bridemobile = $_POST['bride-mobile'];
$groommobile = $_POST['groom-mobile'];
$familymobile = $_POST['family-mobile'];
$email = $_POST['email'];
$refering = $_POST['refering'];
$share = $_POST['share'];
$permission = $_POST['permission'];
// attempt insert query execution
$qry = "insert into personal_detail (Name, CNIC, Date, Ocassion, Address,
Phone_No, Bride_Mobile, Groom_Mobile,
Family_Mobile,EMail,Referring,Share,Permission) values
('$name','$cnic','$date','$ocassion','$address','$phoneno','$bridemobile','$gro
ommobile','$familymobile','$email','$refering','$share','$permission')";
if(mysqli_query($con,$qry))
{
$message = "Record Saved Successfully";
echo "<script type='text/javascript'>alert('$message');</script>";
}
else
{
$message = "Record Insertion Failed!";
echo "<script type='text/javascript'>alert('$message');</script>";
}
I have another table it's working completely fine. Means saves records into the table if the entries in the form are made as required.To me the syntax of both is looking completely same, but don't why the one not working: the PHP code that' working fine for other table is given below:
<?php
$server="localhost";
$user="root";
$password="";
$database="camouflage_studio";
$con = mysqli_connect($server,$user,$password,$database);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST['submit'])){
$name = $_POST['name'];
$cn = $_POST['contact-number'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
//query
$qry = "insert into contact_us (Name,Contact_No,EMail,Subject,Message) values ('$name','$cn','$email','$subject','$message')";
if(mysqli_query($con,$qry))
{
$message = "Record Saved Successfully";
echo "<script type='text/javascript'>alert('$message');</script>";
}
else
{
$message = "Record Insertion Failed!";
echo "<script type='text/javascript'>alert('$message');</script>";
}
}
mysqli_close($con);
?>
#Muhammad Aatif here i have a similar example of your with same column and table name.
I have used mysqli_real_escape_string($conn, $_POST['name_of_form']) against SQL INJECTION to know more you can visit this site sql injection link
HERE IS THE HTML FORM CODE IN FILE NAME: INDEX.PHP
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<form action="process.php" method="post">
<p>enter name</p>
<input type="text" name="name"><br>
<p>enter cnic</p>
<input type="text" name="cnic"><br>
<p>enter data</p>
<input type="date" name="date"><br>
<p>enter Occassion</p>
<input type="text" name="ocassion"><br>
<p>enter Address</p>
<input type="text" name="address"><br>
<p>enter phone_no</p>
<input type="text" name="phone_no"><br>
<p>enter Bride mobil</p>
<input type="text" name="bride_mobile"><br>
<p>enter Groom mobile</p>
<input type="text" name="groom_mobile"><br>
<p>enter family mobile</p>
<input type="text" name="family_mobile"><br>
<p>enter email</p>
<input type="text" name="email"><br>
<p>enter Referring</p>
<input type="text" name="referring"><br>
<p>enter share</p>
<input type="text" name="share"><br>
<p>enter permission</p>
<input type="text" name="permission"><br>
<input type="submit" name="Submit-Personal"><br>
</form>
</body>
</html>
HERE IS THE PHP CODE IN FILE NAME: PROCESS.PHP
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "demo";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['Submit-Personal'])){
$name = mysqli_real_escape_string($conn, $_POST['name']);
$cnic = mysqli_real_escape_string($conn, $_POST['cnic']);
$date = mysqli_real_escape_string($conn, $_POST['date']);
$ocassion = mysqli_real_escape_string($conn, $_POST['ocassion']);
$address = mysqli_real_escape_string($conn, $_POST['address']);
$phone_no = mysqli_real_escape_string($conn, $_POST['phone_no']);
$bride_mobile = mysqli_real_escape_string($conn, $_POST['bride_mobile']);
$groom_mobile = mysqli_real_escape_string($conn, $_POST['groom_mobile']);
$family_mobile = mysqli_real_escape_string($conn, $_POST['family_mobile']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$referring = mysqli_real_escape_string($conn, $_POST['referring']);
$share = mysqli_real_escape_string($conn, $_POST['share']);
$permission = mysqli_real_escape_string($conn, $_POST['permission']);
$sql = "INSERT INTO personal_detail (Name,CNIC, Date,Ocassion,Address,Phone_No,Bride_Mobile,Groom_Mobile,Family_Mobile,EMail,Referring,Share,Permission) VALUES ('$name','$cnic','$date','$ocassion','$address','$phone_no','$bride_mobile','$groom_mobile', '$family_mobile','$email','$referring','$share','$permission')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
echo "<script type='text/javascript'>alert('sucess');</script>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
?>
HERE IS THE OUTPUT RESULT
HERE IS THE TABLE IMAGE
FEEL FREE TO ASK MORE QUESTIONS
The proper way to prevent sql injection is to use MYSQLI->PREPARED STATEMENT CLICK ON THIS LINK TO GET BREIF DETAIL SQL INJECTION

Get and insert Data into MySQL database using PHP with xampp on localhost

I have managed to connect to database and I manage to insert using following code.
<?php
$username = 'root';
$password = '';
$db = 'demo';
$conn = new mysqli ('localhost',$username, $password, $db) or die("unable to connect");
$sql="insert into persons (first_name,last_name,email_address) values ('sara','smith','email#email.com')";
$query=mysqli_query($conn,$sql);
if($query)
echo 'data inserted';
?>
But the problem is that when I try to enter data using HTML form, it didn't work for me. I have tried to follow different tutorials and different answers here on stackoverflow. Can anyone please tell me the easiest way of inserting and getting data from MySQL using PHP ?
If there is any easy tutorial or blog from where i can learn and understand all this, I would love to watch or read.
I manage to do it in following way.
Create a file name index.php with following code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add Record Form</title>
</head>
<body>
<form action="insert.php" method="post">
<p>
<label for="firstName">First Name:</label>
<input type="text" name="firstname" id="firstName">
</p>
<p>
<label for="lastName">Last Name:</label>
<input type="text" name="lastname" id="lastName">
</p>
<p>
<label for="emailAddress">Email Address:</label>
<input type="text" name="email" id="emailAddress">
</p>
<input type="submit" value="Submit">
</form>
</body>
</html>
Then create another file name as insert.php
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$first_name = mysqli_real_escape_string($link, $_POST['firstname']);
$last_name = mysqli_real_escape_string($link, $_POST['lastname']);
$email_address = mysqli_real_escape_string($link, $_POST['email']);
// attempt insert query execution
$sql = "INSERT INTO persons (first_name, last_name, email_address) VALUES ('$first_name', '$last_name', '$email_address')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>
//procedural style
$mysqli = mysqli_connect('host','username','password','database_name');
//Output any connection error
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
//inserting a record
$product_code = '"'.$mysqli->real_escape_string('P1234').'"';
$product_name = '"'.$mysqli->real_escape_string('42 inch TV').'"';
$product_price = '"'.$mysqli->real_escape_string('600').'"';
//MySqli Insert Query
$insert_row = $mysqli->query("INSERT INTO products (product_code, product_name, price) VALUES($product_code, $product_name, $product_price)");
if($insert_row){
print 'Success! ID of last inserted record is : ' .$mysqli->insert_id .'<br />';
}else{
die('Error : ('. $mysqli->errno .') '. $mysqli->error);
}
A quick and untested example of using an HTML form with the POST method to insert data entered by a user into the db.
<?php
$result = false;
$dbhost = 'localhost';
$username = 'root';
$password = '';
$db = 'demo';
if( $_SERVER['REQUEST_METHOD']=='POST' ){
$conn = new mysqli ( $dbhost,$username, $password, $db );
if( $conn ){
$sql='insert into `persons` ( `first_name`,`last_name`,`email_address` ) values (?,?,?);';
$stmt=$conn->prepare( $sql );
$stmt->bind_param('sss', $_POST['firstname'], $_POST['lastname'], $_POST['email'] );
$result = $stmt->execute();
}
$conn->close();
}
?>
<!doctype html>
<html>
<head>
<title>Simple Form submission example</title>
</head>
<body>
<form method='post'>
<input type='text' name='firstname' />
<input type='text' name='lastname' />
<input type='text' name='email' />
<input type='submit' value='Submit' />
<?php
echo $result ? '<div>The database was updated</div>' : '';
?>
</form>
</body>
</html>
Try tutsplus or lynda, Provide you with the best tuto !

Php form value not matching [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 7 years ago.
I have reviewed the code and everything appears right so I am not sure what is wrong. I keep getting the following error s1s01 1136 column count does match.
I believe I used all the correct security codes please note if I did not thank you.
<?php
include ('wording/en-translation.php');
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
</head>
<body>
<?php
// define variables and set to empty values
$user_nameErr = $user_emailErr = "";
$user_name = $user_email = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["user_name"])) {
$user_nameErr = "Name is required";
} else {
$user_name = mysql_real_escape_string($_POST["user_name"]);
//check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z]*$/",$user_name)) {
$user_nameErr="Only letters and white spaces allowed";
}
}
if (empty($_POST["user_email"])) {
$user_emailErr = "Email is required";
} else {
$user_email = mysql_real_escape_string($_POST["user_email"]);
//check if email is well-formed
if (!filter_var($user_email, FILTER_VALIDATE_EMAIL)) {
$user_emailErr = "Invalid Email Format";
}
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$user_name = mysql_real_escape_string($_POST["user_name"]);
$user_email = mysql_real_escape_string($_POST["user_email"]);
}
function mysql_real_escape_string($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<label for="user_name"><?php echo WORDING_REGISTRATION_USERNAME; ?></label>
<input id="user_name" type="text" pattern="[a-zA-Z0-9]{2,64}" value="<?php echo $user_name; ?>" name="user_name" required />
<span class="error">* <?php echo $user_nameErr;?></span><br>
<label for="user_email"><?php echo WORDING_REGISTRATION_EMAIL; ?></label>
<input id="user_email" type="email" name="user_email" value="<?php echo $user_email; ?>" required />
<span class="error">* <?php echo $user_emailErr;?></span>
<input type="submit" name="register" value="<?php echo WORDING_REGISTER; ?>" />
</form>
<?php
echo $user_name;
echo "<br>";
echo $user_email;
echo "<br>";
?>
<?php
$servername = "localhost";
$username = "admin";
$password = "";
$dbname = "login";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO users(user_name, user_email)
VALUES(
". mysql_real_escape_string($user_name) ."',
". mysql_real_escape_string($user_email) ."'
)";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
</
You're generating broken SQL, by having completely WRONG quoting on your values:
$sql = "INSERT INTO users(user_name, user_email)
VALUES(
". mysql_real_escape_string($user_name) ."',
^---start sql string
". mysql_real_escape_string($user_email) ."'
^---end of sql string
)";
That means you're generating
INSERT INTO users (user_name, user_email) VALUES (Bob, 'bob#example.com')
^--unknown field
you're also mixing mysql libraries, which is flat out IMPOSSIBLE, and you're vulnerable to sql injection attacks.
In short, this code is totally cargo-cult programming, and you really need to sit back and learn PHP properly.

html text form with php isn't inserting into MySQL server

I am writing code that produces a <textarea> for a user to input something but it isn't giving me any output besides "please include some content" which is what it means to do if there is nothing in the box. This appears even if there is content in the <textarea> and won't even say "post fail" which is what it is meant to do if it can't insert into the database.
I am asking if anybody can see if there is something I have neglected to include, or if there is something that is wrong with my code.
<?php
session_start();
require('connect.php');
if(#$_SESSION["name"]){
//echo "welcome ".$_SESSION['name'];
?>
<html>
<link rel="stylesheet" type="text/css" href="styles.css" />
<head>
<title> Welcome to faecesbook</title>
</head>
<?php include('header.php'); ?>
<form action="post.php" method="POST">
<br / >
<br / >
<br / >
<br / >
<center>
<br/>
<br/>
Type your post here:<br/>(160CharLimit)<br/>
<textarea style="resize: none; width: 800px; height: 100px;" name="con" maxlength="160">
</textarea>
<br />
<input type="submit" name="submit" value="Post" style="width: 800px;" >
</center>
</form>
<body>
</body>
</html>
<?php
$content = #$_POST['con'];
$post_date = date("d-m-y");
if(isset($_POST['submit'])){
if($content){
if($query = mysqli_query($conn, "INSERT INTO post(`postID`, `userID` , `post_date` , `in_reply_to`, `postContent` )
VALUES ('','".$_SESSION["userID"]."','".$post_date."','','".$content."')") )
echo "post successful";
}else{
echo "post fail";
}
}else{
echo "Please include some content";
}
}
?>
Try this code. It should work.
<?php
session_start();
require('connect.php');
if(#$_SESSION["name"]){
//echo "welcome ".$_SESSION['name'];
?>
<html>
<link rel="stylesheet" type="text/css" href="styles.css" />
<head>
<title> Welcome to faecesbook</title>
</head>
<?php include('header.php'); ?>
<form action="post.php" method="POST">
<br / >
<br / >
<br / >
<br / >
<center>
<br/>
<br/>
Type your post here:<br/>(160CharLimit)<br/>
<textarea style="resize: none; width: 800px; height: 100px;" name="con" maxlength="160">
</textarea>
<br />
<input type="submit" name="submit" value="Post" style="width: 800px;" >
</center>
</form>
<body>
</body>
</html>
<?php
$post_date = date("d-m-y");
if(isset($_POST['submit'])){
if(isset($_POST['con']) && $_POST['con'] != ''){
$content = #$_POST['con'];
if($query = mysqli_query($conn, "INSERT INTO post(`postID`, `userID` , `post_date` , `in_reply_to`, `postContent` )
VALUES ('','".$_SESSION["userID"]."','".$post_date."','','".$content."')") )
echo "post successful";
}else{
echo "post fail";
}
}else{
echo "Please include some content";
}
}
?>
You have a missing braces in your code
if(#$_SESSION["name"]){
//echo "welcome ".$_SESSION['name'];
Should read
if(#$_SESSION["name"]){
//echo "welcome ".$_SESSION['name'];
}
And
if($query = mysqli_query($conn, "INSERT INTO post(`postID`, `userID` , `post_date` , `in_reply_to`, `postContent` )
VALUES ('','".$_SESSION["userID"]."','".$post_date."','','".$content."')") ) // <--- here
echo "post successful";
}else{
echo "post fail";
}
Making it readable also helps reduce errors
$query = mysqli_query($conn, "INSERT INTO post(`postID`, `userID` , `post_date` , `in_reply_to`, `postContent` )
VALUES ('','".$_SESSION["userID"]."','".$post_date."','','".$content."')");
if ($query){
echo "post successful";
}else{
echo "post fail";
}
I see your code sends submited data to another page, i checked it through print_r($_POST)
I changed <form action="post.php" method="POST"> to <form action="" method="POST"> and tried and it was working, in case if the code you submited here is not "post.php" do this.
So it means someting is wrong with your insert query. So try this PDO way of inserting data.I thought of suggesting you the following easy pdo insert
$dbhost = "localhost";
$dbname = "mydatabase";
$dbusername = "root";
$dbpassword = "mypppasss";
//connection string
$link = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbusername,$dbpassword);
Inside the if($content) put the following code and try
$statement = $link->prepare("INSERT INTO post(userID,post_date,postContent)
VALUES(:inp1,:inp2,:inp3,:inp4)");
$statement->execute(array(
inp1=>$_SESSION["userID"],
inp2=>$post_date,
inp4=>$content
));
EDITED
Add this code to the form submitted page to see the posted data for debugging.
if($_POST){
echo '<pre>';
print_r($_POST);
echo '</pre>';
}
EDITED
Note:# is used to hide errors, prevent it from displaying error
messages. that doesn't mean there is no error. Remove # for debugging
EDITED
Change your whole insert query part to this and try
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO post(userID,post_date,in_reply_to,postContent)
VALUES (".$_SESSION['userID'].",".$post_date.",'',".$content.")";
if (mysqli_query($conn, $sql)) {
echo "inserted";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
This is what was wrong.
i had two set of <?php ?>, the first one in the code included require('connect.php'); within it, and the second one required it also.
<?php
require('connect.php'); <<<<<------ NEEDED TO ADD THIS
$content = #$_POST['con'];
$post_date = date("d-m-y");
$userID = mysqli_query($conn,"SELECT userID FROM users WHERE name = '".$_SESSION['name']."'");
if(isset($_POST['submit'])){
if($content){
if($query = mysqli_query($conn, "INSERT INTO post(`postID`, `userID` , `post_date` , `in_reply_to`, `postContent` )
VALUES ('','".$userID."','".$post_date."','','".$content."')") )
echo "post successful";
}else{
echo "post fail";
}
}else{
echo "Please include some content";
}
}
?>
So thats what i think the offending piece of code was. And it now will give me error saying the SQLI query was unnsuccessful, which means it is at least attempting that part, whereas before it was not.

Categories