display user input as comment on same page - php

I'm trying to create a comment system on my webpage. I want the user to be able in input a comment and have it automatically display on the same page, and reload so that if another user wants to comment the previous comment will also be there. So far, I have created a database that takes in the comments. I have tried to display the comments by querying through my database and printing it out, but it just seems to crash my site.
This is the code I have so far
index.php:
<form action="insert.php" method="GET">
Comments:
<input type="text" name="field1_name"/>
<input type="submit" name="submit" value="submit"/>
</form>
<?php
$query="SELECT COMMENTS FROM parentComment";
$results = mysqli_query($query);
while ($row = mysqli_fetch_assoc($results)) {
echo $row['COMMENTS'];
}
?>
insert.php:
$user = 'x';
$password = '';
$db = 'comment_schema';
$host = 'localhost';
$port = 3306;
$link = mysqli_connect($host, $user, $password, $db);
mysqli_query($link,"GRANT ALL ON comment_schema TO 'x'#'localhost'");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if(!empty($_GET["field1_name"])) {
$field1_name = mysqli_real_escape_string($link, $_GET["field1_name"]);
// Escape user inputs for security
$sql = "INSERT INTO parentComment (COMMENTS) VALUES ('$field1_name')";
$result = mysqli_query($link, $sql);
// attempt insert query execution
if ($result) {
//echo $_GET["field1_name"];
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
}
else{
die('comment is not set or not containing valid value');
}
So far everything works as in the comments are being inserted into the database. My problem is with retrieving the comments and displaying it to the user on the same page. I've tried to do so, but it seems to be not working. Not sure where I'm going wrong in my implementation (I've implemented it in the index.php file)

You didn't connect to your db for the query:
$results = mysqli_query($query);
Pass the connection to the query:
$results = mysqli_query($link, $query);
It's required.
http://php.net/manual/en/mysqli.query.php
You also need to make sure that you did establish a connection in that file, otherwise it won't work.

Related

How to figure out if row is equal to a specific input

I am trying to figure out how to get a specific input from a database and fetching it. If its not equal to 1 do function.
Example code:
$admincheck = "SELECT admin FROM users";
if($admincheck == 0){
echo "<p style='font-size:40px;text-align:center;'><strong>Du har ikke tilgang til å se dette innholdet.</p>";
In my user database i have Username, Password, Admin.
Admin is default 0. If the number is 1 i want to grant access to that specific website.
You will need to connect to the database and then run your query. You will get a resultset back and you get the value you want from the resultset. Then you can do whatever you need to do with the result.
Try something like the following (most of this was pulled from: https://www.php.net/manual/en/mysqli.query.php):
$mysqli = new mysqli("localhost", "username", "password", "databasename");
$username = "whatever username you are checking";
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
if ($result = $mysqli->query("select admin from users where username='$username'")) {
while($obj = $result->fetch_object()){
$is_admin = $obj->admin;
if ($is_admin === 0){
echo "whatever html you want to echo";
}
}
/* free result set */
$result->close();
}
$mysqli->close();
You will need to make sure that your database prevents more than one person from having the same username, I recommend adding a unique index on username. Usually people have an additional column called "id" that auto_increments so that it will always be a unique number and that's a lot easier to work with.
I recommend abstracting this logic into a separate file that will be responsible for verifying that the user is authenticated.
this query is not for one column
$admincheck = "SELECT admin FROM users";
you should add a where condition and after that, you can check if($admincheck == 0)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT admin FROM users where id=1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
if($row->admin_check == 1){
/////this is your code to check admin...
}
}
} else {
echo "0 results";
}
$conn->close();
?>

php search works as seperate page, but not on same page

I'm working on a project where I can use multiple forms on an html page to search and update tables from a mysql database. I have created a basic html form that will run a search on a separate php file. When I try to integrate that same php script into that same html it finds no results. Any help would be appreciated.
basic html
<html>
<body>
<form name="search" method="post" action="searchresults.php">
<input name="search" type="text" size="40" maxlength="50" />
<input type="submit" name="Submit" value="Search" />
</form>
</body>
</html>
search php
<?php
$database = "dbname";
$username = "name";
$password = "pass";
$host = "host";
$conn = new mysqli($host, $username, $password, $database);
if ($conn->connect_error){
die("Failed:" . $conn->connect_error);
}
echo"Successful";
$query = $_POST['search'];
$query = htmlspecialchars($query);
$raw_results = mysqli_query($conn,"SELECT * FROM beers WHERE name LIKE '%".$query."%'");
if(mysqli_num_rows($raw_results) > 0){ // if one or more rows are returned do following
while($results = mysqli_fetch_array($raw_results)){
echo "<p><h3>".$results['Name']."</h3>".$results['Brewery']."</p>";
}
}
else{ // if there is no matching rows do following
echo "No results";
}
?>
This works separated, but if I copy the same php script and insert it into the main html it connects but finds no results. Tried using _GET instead of _POST removed the action field and Ive searched all over for similar issues. If I scale everything completely down it gives me a parse error for $query = htmlspecialchars($query); , any thoughts?
Apply if (isset($query)) {...}. Only when search name is valid can you gain results.
<?php
$query = $_POST['search'];
// Apply validation.
if (isset($query)) {
$query = htmlspecialchars($query);
echo"Successful";
$conn = new mysqli($host, $username, $password, $database);
if ($conn->connect_error) {
die("Failed:" . $conn->connect_error);
}
$raw_results = mysqli_query($conn, "SELECT * FROM beers WHERE name LIKE '%" . $query . "%'");
if (mysqli_num_rows($raw_results) > 0) { // if one or more rows are returned do following
while ($results = mysqli_fetch_array($raw_results)) {
echo "<p><h3>" . $results['Name'] . "</h3>" . $results['Brewery'] . "</p>";
}
} else { // if there is no matching rows do following
echo "No results";
}
}
?>

I GET "No database selected" ERROR even that is selected

Im new in MySql and PHP and im trying to make a CRUD but everytime i try to insert data into table called "studenti" i get the error that i didnt select a database but i selected a database with mysqli_select_db($con, "d_base");
Somebody please help me cuz i dont understand why its not workin'
Here is the code;
$id = $_POST['ID'];
$nota = $_POST['Nota'];
$emri = $_POST['Emri'];
$mbiemri = $_POST['Mbiemri'];
$servername = "localhost";
$dbname = "d_base";
// 1.Create connection
$con = mysqli_connect("localhost","d_base");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (!mysqli_query($con,"INSERT INTO studenti (id, nota, emri, mbiemri) VALUES ('$id', '$nota','$emri','$mbiemri')"))
{
echo("Error description: " . mysqli_error($con));
}
// Perform queries
mysqli_select_db($con, "d_base");
mysqli_query($con,"INSERT INTO studenti (id, nota, emri, mbiemri) VALUES ('$id', '$nota','$emri','$mbiemri')");
mysqli_close($con);
Before all that if you are a begginer go straight on PDO or use mysqli with prepared statements its safer.
Here is example how your php and html form must look like and work.
First you must check if submit button is pressed, if its pressed read values form form $_POST variables.
Second thing you must escape injection to your mysql by using function mysqli_real_escape_string().
After that try to insert query and check for error, if there is no error query will be inserted successfully.
PHP code
<?php
// set error report ; 1 = on | 0 = off
error_reporting(1);
$db_host = "localhost"; // host
$db_user = "root"; // database username
$db_pass = ""; // database password
$db_name = "d_base"; // database name
// 1.Create connection
$con = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// if form is submited
if (isset($_POST['submit']))
{
// escape post variables
$id = mysqli_real_escape_string($con, $_POST['ID']);
$nota = mysqli_real_escape_string($con, $_POST['Nota']);
$emri = mysqli_real_escape_string($con, $_POST['Emri']);
$mbiemri = mysqli_real_escape_string($con, $_POST['Mbiemri']);
// make query
$query = mysqli_query($con, "INSERT INTO studenti (id, nota, emri, mbiemri VALUES ('$id', '$nota', '$emri', '$mbiemri')")
// check for query
if (!$query)
{
echo "Error description: " . mysqli_error($con);
}
else
{
echo "Query inserted.";
}
// close connenction
mysqli_close($con);
}
?>
<form action="" method="post">
<input type="text" name="ID" placeholder="Id"><br />
<input type="text" name="Nota" placeholder="Nota"><br />
<input type="text" name="Emri" placeholder="Emri"><br />
<input type="text" name="Mbiemri" placeholder="Mbiemri"><br />
<input type="submit" name="submit" value="Submit form">
</form>

PHP $_POST empty -- not working for local server using MAMP

So currently, this is the code I have
index.php:
<form action="insert.php" method="post">
Comments:
<input type="text" name="comment">
<input type="submit">
</form>
insert.php:
<?php
include ('index.php');
$user = 'x';
$password = '';
$db = 'comment_schema';
$host = 'localhost';
$port = 3306;
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "x", "", "comment_schema");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$comment = mysqli_real_escape_string($link, $_POST["comment"]);
$sql = "INSERT INTO parentComment(ID, Comment) VALUES('','$comment')";
// attempt insert query execution
if(mysqli_query($link, $sql)){
echo $comment;
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
When I do echo $comment, nothing gets printed out. However, if I do something like echo "hi" it works. I think for some reason the $_POST is not being recognized. Any suggestions to make this work or if I'm doing it wrong.
My goal is to take a user input and insert into a database on phpmyadmin. Currently, it is able to insert, however it inserts an empty value. I only have two columns in my database. An ID and a Comment column. The ID is auto incremented. The comment is what I get from the user.
Check Once what is your data type of comment in database.(I prefer Varchar()).
Try this as it is:-
<form action="insert.php" method="POST">
Comments:
<input type="text" name="comment"/>
<input type="submit" name="submit" value="submit">
</form>
<?php
include ('index.php');
$user = 'x';
$password = '';
$db = 'comment_schema';
$host = 'localhost';
$port = 3306;
$link = mysqli_connect("localhost", "x", "", "comment_schema");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$comment = mysqli_real_escape_string($link, $_POST["comment"]);
$sql = "INSERT INTO parentComment(ID, Comment) VALUES('','$comment')";
if(mysqli_query($link, $sql)){
echo $comment;
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
try this
<?php
$user = 'x';
$password = '';
$db = 'comment_schema';
$host = 'localhost';
$link = mysqli_connect($host, $user, $password, $db);
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$comment = mysqli_real_escape_string($link, $_POST["comment"]);
$sql = "INSERT INTO parentComment(ID, Comment) VALUES(NULL,'$comment')";
// attempt insert query execution
if(mysqli_query($link, $sql)){
echo $comment;
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
Use below code:-
include ('index.php');
$user = 'x';
$password = '';
$db = 'comment_schema';
$host = 'localhost';
$port = 3306;
$link = mysqli_connect("localhost", "x", "", "comment_schema");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if(!empty($_POST["comment"])){
$comment = mysqli_real_escape_string($link, $_POST["comment"]);
// Escape user inputs for security
$sql = "INSERT INTO parentComment(ID, Comment) VALUES('','$comment')";
$result = mysqli_query($link, $sql);
// attempt insert query execution
if($result){
echo $comment;
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
}else{
die('comment is not set or not containing valid value');
}
Hope it will help you :-)
Some debugging suggestions:
var_dump($_POST); // before mysqli_real_escape_string
var_dump($comment); // after mysqli_real_escape_string
mysqli api may not work well! Fix the query like
$sql = "INSERT INTO parentComment(ID, Comment) VALUES('','".$comment."')";
echo $sql; // check your sql syntax
echo mysqli_error($link); // do you have error
Look at your .htaccess file see if you have <Limit POST> tag
Remove this line include ('index.php');. Supposedly, these two files are in one folder. So just run index.php . Tried your code without that line and it worked for me.

Running php functions on the same screen

Hi I'm very very new to php and playing with codes to learn. I have a very basic login form that has username and password input and two input buttons
one to create entries in the database and other to read from database.
JsFiddle: https://jsfiddle.net/e93kcpto/
My sign up and read functions are located in functions.php file
function signUpFunct(){
if(isset($_POST['username']) and isset($_POST['password'])){
$username = $_POST['username'];
$password = $_POST['password'];
$connection = mysqli_connect('localhost','root','','loginPage');
if($connection){
$query = "INSERT INTO users(username,password) VALUES ('$username','$password')";
if($query){
mysqli_query($connection,$query);
}
else{
die("Sign Up Failed");
}
}
else{
die("Failed to Connect Database");
}
}
}
function readAll(){
$connection = mysqli_connect('localhost','root','','loginPage');
if($connection){
$query = "SELECT * FROM users";
if($query){
$result = mysqli_query($connection,$query);
while($row = mysqli_fetch_assoc($result)){
?>
<pre>
<?php print_r($row);?>
</pre>
<?php
}
}
else{
die("Sign Up Failed");
}
}
else{
die("Failed to Connect Database");
}
}
and this is how I call these two functions in the functions.php file(I'm not sure if this is a good approach so if there is a better way please let me know)
if(isset($_POST['signUp'])){
signUpFunct();
}
else if(isset($_POST['display'])){
readAll();
}
both functions work fine but the problem is when I click on the display button in the browser I am at http://localhost.../functions.php
what I would like to do is to display the data on the form page when I click on the Display button. How can I do this?

Categories