Getting items from a database not working as expected - php

I'm learning PHP and I've hit a wall.
When the user submits to the form, it adds to the database.
I am also trying to display all items in the database on the same page as the form.
However,this only works if the form has just been submitted. If the form has not been submitted (but there is still content in the database), nothing is shown.
How can I always show what is in the current database?
<form action="" method="post">
<input type="text" name="todo_content" id="">
<input type="submit" value="Submit">
</form>
<?php
if ( isset($_POST['todo_content'])) {
$latest_content = $_POST['todo_content'];
} else {
die();
}
$todo_db = mysqli_connect('localhost', 'root', 'root');
mysqli_select_db($todo_db, 'todo_list');
mysqli_query(
$todo_db,
"INSERT INTO todo_items (item_content) VALUES ('$latest_content')"
);
$all_todos = mysqli_query( $todo_db, "SELECT item_content FROM todo_items" );
$all_todos_result = mysqli_fetch_array($all_todos);
var_dump($all_todos_result); // these show nothing
var_dump($all_todos); // these show nothing
?>

The die() is your problem:
if ( isset($_POST['todo_content'])) {
echo 'is set';
$latest_content = $_POST['todo_content'];
} else {
die();
}
If $_POST is not set, you will never reach the part where you start printing your items. And since the form is not submitted, $_POST is empty.
EDIT
You could do it like this:
<form action="" method="post">
<input type="text" name="todo_content" id="">
<input type="submit" value="Submit">
</form>
<?php
$todo_db = mysqli_connect('localhost', 'root', 'root');
mysqli_select_db($todo_db, 'todo_list');
if ( isset($_POST['todo_content'])) {
$latest_content = $_POST['todo_content'];
mysqli_query($todo_db, "INSERT INTO todo_items (item_content) VALUES ('$latest_content')");
}
$all_todos = mysqli_query( $todo_db, "SELECT item_content FROM todo_items" );
$all_todos_result = mysqli_fetch_array($all_todos);
var_dump($all_todos_result); // these show nothing
var_dump($all_todos); // these show nothing
?>

You need to move your insert query inside your if condition and you will need not to die if the form is not submitted but print the form and your query results
$todo_db = mysqli_connect('localhost', 'root', 'root');
mysqli_select_db($todo_db, 'todo_list');
if ( isset($_POST['todo_content'])) {
echo 'is set';
$latest_content = $_POST['todo_content'];
mysqli_query($todo_db, "INSERT INTO todo_items (item_content) VALUES ('$latest_content')");
} else {
?>
<form action="" method="post">
<input type="text" name="todo_content" id="">
<input type="submit" value="Submit">
</form>
<?php
$all_todos = mysqli_query( $todo_db, "SELECT item_content FROM todo_items" );
$all_todos_result = mysqli_fetch_array($all_todos);
var_dump($all_todos_result);
var_dump($all_todos);
}
As side note i'd say you are at high risk of mysql injection. You should use prepaed statments and not inserting $_POST data inside your database directly

Related

If clause does not give update only works insertion. Why update is not working?

I want to update and insert conditionally but query always goes "Insert" data. No "update" anyway. My code is below:
<form method="post" action="">
<label>ID: </label> <input type="text" name="id">
<label>Subject: </label> <input type="text" name="subject">
<input type="submit" name="submit">
</form>
<?php
$conn = new mysqli("localhost", "root", "", "zidm");
$id=$_POST['id'];
$subject=$_POST['subject'];
if (isset($_POST['submit'])){
$sql = "UPDATE exam SET subject = '$subject' WHERE id = '$id'";
mysqli_query($conn,$sql);
echo "Data Updated";
}
else {
$sql="INSERT INTO exam (subject) VALUES ( '$subject)";
mysqli_query($conn,$sql);
echo "Data Inserted";
}
?>
The issue is that you are checking for form submission but also have an else statement which will always fire on page load. You need to wrap your entire logic in the form submission check and then check for the id parameter.
// Form was submitted
if (isset($_POST['submit'])) {
if (!empty($_POST['id'])) {
// Update
} else {
// Insert
}
}

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?

Dynamic insert into with multiple values

This is my index.php file and it has a simple form but with jscript I'll add some more inputs dynamically, then I need to insert these inputs to my database.
<form action="insert.php" method="post">
<input type="text" name="uid" placeholder="uid">
<input type="text" name="cid_1" placeholder="cid1">
<input type="text" name="cid_2" placeholder="cid2">
<input type="submit" value="Register" name="submit" />
</form>
I've created insert.php as below. I just needed to type for each inputs but actually inputs will be added dynamically as I said, so I just need to apply while or foreach function I guess but I'm not that sure how to do, hope someone there can help me about this.
One more thing I need, In this case everything is working but it inserts everytime even if some inputs are empty. I could not found anything about this too.
Thank you for your help from now.
<?php
$link = mysqli_connect("localhost", "root", "", "test");
$uid = mysqli_real_escape_string($link, $_POST['uid']);
$cid1 = mysqli_real_escape_string($link, $_POST['cid_1']);
$cid2 = mysqli_real_escape_string($link, $_POST['cid_2']);
$sql = "INSERT INTO table (uid, cid) VALUES ('$uid', '$cid1'), ('$uid', '$cid2')";
mysqli_query($link, $sql)
?>
From your SQL query I understood that under uid, you are storing dynamic "cid" values from input. So you are adding dynamic input fields for "cid".
In order to capture dynamic fields on server, you have to name your input fields as given below which will be posted as an array on server.
<input type="text" name="cid[]" placeholder="cid1">
Next you will loop through that array and save each input data in your table.
Complete code:
HTML
<form action="insert.php" method="post">
<input type="text" name="uid" placeholder="uid">
<input type="text" name="cid[]" placeholder="cid1">
<input type="text" name="cid[]" placeholder="cid2">
<input type="submit" value="Register" name="submit" />
PHP
$mysqli = new mysqli('localhost','usename','password','table');
$uid = $mysqli->real_escape_string($_POST['uid']);
if($uid !== ''){
if(isset($_POST["cid"]) && is_array($_POST["cid"])){
foreach ($_POST["cid"] as $key => $value) {
$value = $mysqli->real_escape_string($value);
if($value !== ''){
// insert into table
$insert_row = $mysqli->query("INSERT INTO test ( uid, cid ) VALUES( '$uid', '$value' )");
}
else{
echo ($key+1)." no cid field is empty";
break;
}
}
}
}
else
echo "uid is empty";

What's wrong with my data submisson system[one button, 2 fields]

I am setting up my custom blog's basic submission system.
This is the PHP section of it that I try to submit the inserted data into the database
<?php
session_start();
if(!isset($_SESSION['user_id'])){
header('Location: login.php');
exit();
}
include('../includes/db_connect.php');
if(isset($_POST['submit'])){
$newTitle = $_POST['newTitle'];
$newPost = $_POST['newPost'];
$my_date = date("Y-m-d H:i:s");
if(!empty($newPost))
if(!empty($newTitle)){
$sql="INSERT INTO posts (title, body)
VALUES($newTitle, $newPost)";
$query = $db->query($sql);
if($query){
echo "Post entered to database";
}else{
echo "Error Submitting the data";
}
}
}
?>
Then There is the submission form, I am pretty sure this is the faulty end for some reason, but I cannot find out why.
<form action="<?php echo $_SERVER['PHP_SELF']?>"name="newTitle" method="post">
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
<p>Title:</p><br><input type="text" name="newTitle">
<textarea name="newPost" cols="110" rows="25"/></textarea><br>
<label for="newPost">Add New Post</label><input type="submit" name="submit" value="submit"/>
</form>
This is the database's table:
post_id (A_I)
user_id
title
body
category_id
posted(datetime)
Bear in mind that I am a rookie in this area, so don't be too harsh :)
Use single quote for strings:
$sql="INSERT INTO posts (title, body) VALUES ('$newTitle', '$newPost')";
//^ ^ ^ ^
Notice:
Try to use PDO and param binding in your projects to prevent sql injection.
Nice Tutorial about PDO
Use single form tag only:
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
<p>Title:</p><br><input type="text" name="newTitle">
<textarea name="newPost" cols="110" rows="25"/></textarea><br>
<label for="newPost">Add New Post</label>
<input type="submit" name="submit" value="submit"/>
</form>
And in your php code, you can check youe data by using isset() function
if(isset($_POST['submit'])){
if(isset($_POST['newTitle']) && ($_POST['newPost']))
$newTitle = $_POST['newTitle'];
$newPost = $_POST['newPost'];
$my_date = date("Y-m-d H:i:s");
$sql="INSERT INTO posts (title, body)
VALUES('$newTitle', '$newPost')"; //use variable in single quote.
$query = $db->query($sql);
if($query){
echo "Post entered to database";
}else{
echo "Error Submitting the data";
}
}

PHP insert data to Mysql

I am experimenting with PHP and Mysql. I have created a database and table at mu localhost using xampp. I have also created a file that suppose to populate my table by executing a query, but the strange thing is that i get no errors but at the same time no DATA has been inserted into my DataBase:
CODE:
register.php:
<?php
session_start();
if(isset($_POST['submitted'])){
include('connectDB.php');
$UserN = $_POST['username'];
$Upass = $_POST['password'];
$Ufn = $_POST['first_name'];
$Uln = $_POST['last_name'];
$Uemail = $_POST['email'];
$NewAccountQuery = "INSERT INTO users (user_id,username, password, first_name, last_name, emial) VALUES ('$UserN','$Upass', '$Ufn', '$Uln', '$Uemail')";
if(!mysql_query($NewAccountQuery)){
die(mysql_error());
}//end of nested if statment
$newrecord = "1 record added to the database";
}//end of if statment
?>
<html>
<head>
<title>Home Page</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="wrapper">
<header><h1>E-Shop</h1></header>
<article>
<h1>Welcome</h1>
<h1>Create Account</h1>
<div id="login">
<ul id="login">
<form method="post" action="register.php" >
<fieldset>
<legend>Fill in the form</legend>
<label>Select Username : <input type="text" name="username" /></label>
<label>Password : <input type="password" name="password" /></label>
<label>Enter First Name : <input type="text" name="first_name" /></label>
<label>Enter Last Name : <input type="text" name="last_name" /></label>
<label>Enter E-mail Address: <input type="text" name="email" /></label>
</fieldset>
<br />
<input type="submit" submit="submit" value="Create Account" class="button">
</form>
</div>
<form action="index.php" method="post">
<div id="login">
<ul id="login">
<li>
<input type="submit" value="Cancel" onclick="index.php" class="button">
</li>
</ul>
</div>
</article>
<aside>
</aside>
<div id="footer">This is my site i Made coppyrights 2013 Tomazi</div>
</div>
</body>
</html>
I have also one include file which is connectDB:
<?php
session_start();
$con = mysql_connect("127.0.0.1", "root", "");
if(!$con)
die('Could not connect: ' . mysql_error());
mysql_select_db("eshop", $con) or die("Cannot select DB");
?>
Database structure:
database Name: eshop;
only one table in DB : users;
users table consists of:
user_id: A_I , PK
username
password
first_name
last_name
email
I spend a substantial amount of time to work this out did research and looked at some tutorials but with no luck
Can anyone spot what is the root of my problem...?
It is because if(isset($_POST['submitted'])){
you dont have input field with name submitted give the submit button name to submitted
<input name="submitted" type="submit" submit="submit" value="Create Account" class="button">
Check your insert query you have more fields than your values
Change :
$NewAccountQuery = "INSERT INTO users (user_id,username, password, first_name, last_name, email) VALUES ('$UserN','$Upass', '$Ufn', '$Uln', '$Uemail')";
to :
$NewAccountQuery = "INSERT INTO users (user_id,username, password, first_name, last_name, email) VALUES ('','$UserN','$Upass', '$Ufn', '$Uln', '$Uemail')";
Considering user_id is auto increment field.
Your email in query is written wrongly as emial.
Is error reporting turned on?
Put this on the top of your screen:
error_reporting(E_ALL);
ini_set('display_errors', '1');
Some good answers above, but I would also suggest you make use of newer MySQLi / PDO instead of outdated 2002 MySQL API.
Some examples: (i will use mysqli since you wrote your original example in procedural code)
connectDB.php
<?php
$db = mysqli_connect('host', 'user', 'password', 'database');
if (mysqli_connect_errno())
die(mysqli_connect_error());
?>
register.php -- i'll just write out an example php part and let you do the rest
<?php
//i'll always check if session was already started, if it was then
//there is no need to start it again
if (!isset($_SESSION)) {
session_start();
}
//no need to include again if it was already included before
include_once('connectDB.php');
//get all posted values
$username = $_POST['username'];
$userpass = $_POST['password'];
$usermail = $_POST['usermail'];
//and some more
//run checks here for if fields are empty etc?
//example check if username was empty
if($username == NULL) {
echo 'No username entered, try again';
mysqli_close($db);
exit();
} else {
//if username field is filled we will insert values into $db
//build query
$sql_query_string = "INSERT INTO _tablename_(username,userpassword,useremail) VALUES('$username','$userpass','$usermail')";
if(mysqli_query($db,$sql_query_string)) {
echo 'Record was entered into DB successfully';
mysqli_close($db);
} else {
echo 'Ooops - something went wrong.';
mysqli_close($db);
}
}
?>
this should work quite nicely and all you need to add is your proper posted values and build the form to post it, that's all.
<?php
$db = mysqli_connect('host', 'user', 'password', 'database');
if (mysqli_connect_errno())
die(mysqli_connect_error());
?>
register.php -- i'll just write out an example php part and let you do the rest
<?php
//i'll always check if session was already started, if it was then
//there is no need to start it again
if (!isset($_SESSION)) {
session_start();
}
//no need to include again if it was already included before
include_once('connectDB.php');
//get all posted values
$username = $_POST['username'];
$userpass = $_POST['password'];
$usermail = $_POST['usermail'];
//and some more
//run checks here for if fields are empty etc?
//example check if username was empty
if($username == NULL) {
echo 'No username entered, try again';
mysqli_close($db);
exit();
} else {
//if username field is filled we will insert values into $db
//build query
$sql_query_string = "INSERT INTO _tablename_(username,userpassword,useremail) VALUES('$username','$userpass','$usermail')";
if(mysqli_query($db,$sql_query_string)) {
echo 'Record was entered into DB successfully';
mysqli_close($db);`enter code here`
} else {
echo 'Ooops - something went wrong.';
mysqli_close($db);
}
}
?>

Categories