if(isset($_POST()) always false - php

the $_POST array does not get updated for some reason, not sure why.
here is my code, written in a file called database.php:
$user = 'root';
$password = '';
$db = 'comments_schema';
$host = 'localhost:3306';
$mysqli = mysqli_connect('localhost', $user, $password, $db);
$field1_name = "";
if(isset($_POST['field1_name'])) {
$field1_name = $_POST['field1_name'];
}
else {
echo "something is wrong here";
}
$field_name = mysqli_real_escape_string($mysqli, $field1_name);
$sql = 'INSERT INTO parent_comment(commentid, comment) VALUES
('.commentid.', '.$field_name.')';
$result = $mysqli->query($sql);
Here is my index.html portion for that part:
<form action="database.php" method="post">
Comments: <input type="text" name="field1_name"/>
<input type="Submit" name="Submit" value="submit query"/>
</form>
Any reason why isset always returns false in this case?

EDIT: I don't know if this is the case but check your max_input_vars value not to be a low number in php.ini
php_value max_input_vars 6000 //6K is the value you need
//first if checks if the form was submitted first, so you don't always display the error.
if(isset($_POST['Submit'])){
$user = 'root';
$password = '';
$db = 'comments_schema';
$host = 'localhost:3306';
$mysqli = mysqli_connect('localhost', $user, $password, $db);
$field1_name = $_POST['field1_name'] ?? ""; //Use only if you are using PHP 7+ Otherwise leave the code as it was but wrap it inside the outer if.
if(empty($field_name)){
echo "something is wrong here";
}
$field_name = mysqli_real_escape_string($mysqli, $field1_name);
$sql = 'INSERT INTO parent_comment(commentid, comment) VALUES ('.commentid.', '.$field_name.')';
$result = $mysqli->query($sql);
}
More info: https://lornajane.net/posts/2015/new-in-php-7-null-coalesce-operator

Related

Issue in uploading images to MySQL database using PHP

I have this php code to upload image to the database, I have issue
with it and I don't know what is it, the database table name is
images and the fields are id, name VARCHAR(), photo LONGBLOB.
<?php
ini_set('display_errors', '1');
$servername = "";
$username = "";
$password = "";
//$host = "";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
<html>
<body>
<form method="post" enctype="multipart/form-data">
<input type="file" name="image"/>
</br>
</br>
</br>
<input type="submit" name="go" value="Upload"/>
</form>
<?php
if(isset($_POST['go'])){
if(getimagesize($_FILES['image']['tmp_name']) == FALSE){
echo "Select a photo please";
}else {
$image = addslashes($_FILES['image']['tmp_name']);
$name = addslashes($_FILES['image']['name']);
$image = file_get_contents($image);
$image = base64_encode($image);
save_image($image , $name);
}
}
function save_image($image , $name){
$servername = "localhost";
$username = "cl60-shooters";
$password = "dbsjcNs-b";
$conn = new mysqli($servername, $username, $password);
$qry = "insert into images (photo , name) VALUES ('$image','$name')";
$result = mysqli_query($conn,$qry);
if($result){
echo "Successfull upload";
}else{
echo "try Again";
print_r($result);
}
}
?>
</body>
</html>
The result is as shown in the attached screenshot:
Result
Your function neglects to mention the database - you need to supply that as one of the parameters, like:
function save_image($image , $name){
$servername = "localhost";
$username = "cl60-shooters";
$password = "dbsjcNs-b";
$database='xxxxxxxx';/* enter correct db name */
$conn = new mysqli( $servername, $username, $password, $database );
$qry = "insert into images (`photo`, `name`) VALUES ('$image','$name')";
$result = mysqli_query($conn,$qry);
if($result){
echo "Successfull upload";
}else{
echo "try Again";
print_r($result);
}
}
FYI that said your code is vulnerable to sql injection - better to use prepared statements!
You're not using database name in the mysqli constructor. It should be like the following:
$servername = "localhost";
$username = "cl60-shooters";
$password = "dbsjcNs-b";
$database = "database_name_here";
$conn = new mysqli($servername, $username, $password, $database);
Hope it should work now.

Connecting mysqli_query command from external php file

I have been trying to use mysqli_query to connect to database define in an external file but am getting an repeated error as undefined $conn
index.php
<?php
require 'connect.in.php';
include 'loginform.php';
?>
connect.in.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbase = "users";
$conn = mysqli_connect($servername,$username,$password);
if($conn ||!mysqli_select_db($dbase)){
die('error message');
}
?>
loginform.php
<?php
if(isset($_POST['username']) && isset($_POST['password'])){
$username = 'username';
$password = 'password';
if(!empty($username) && !empty($password)){
$query = "SELECT 'id' FROM 'user_list' WHERE 'username'= '$username' AND 'password' = '$password'";
if(mysqli_query($conn, $query)){
echo "correct";
}
else{
echo "false";
}
}
}
?>
<form method="post">
Username:<input type="text" name="username">
Password:<input type="password" name="password">
<input type="submit" value="Login">
</form>
also is it possible to incorporate CSS and Bootstrap in this php files say for loginform.php?
Don't forget to tell mysqli_connect() function what database you are using. I hate to use W3Schools but take a look here, the 4th parameter is the DB you want to use.
connect.in.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbase = "users";
$conn = mysqli_connect($servername,$username,$password, $dbase);
if($conn ||!mysqli_select_db($dbase)){
die('error message');
}
?>
Generally you would want all your CSS and JS files in the <head> element of your index page or your master page. Essentially you could just add the files in your loginform.php file at the top but i would suggest not doing so and place them in your index.php file.

PHP Login Can't login to index.php

Why can't I login to my index.php page its just getting stucked in my login.php page. Please help. Thanks.
<?php
session_start();
$conn = new PDO('mysql:host = localhost;dbname=userdb','root','');
if (isset($_POST['login'])){
$username = $_POST['username'];
$password = $_POST['password'];
$query = $conn->prepare("SELECT COUNT('userID') FROM 'tbl_account' WHERE 'username' = '$username' AND 'password' = '$password' ");
$query->execute();
$count = $query->fetchColoumn();
if ($count == 1){
$_SESSION['username'] = $username;
header("location : index.php");
exit();
}else{
$error = "Your Login Name or Password is invalid";
}
}
?>
<html>
<head>
<title>Login</title>
</head>
<body>
<form action = "?" method = "POST">
<input type = "text" name="username"><br> //username
<input type = "password" name = "password"><br> //password
<input type = "submit" name = "submit" value = "Login"> /button
</form>
</body>
</html>
where could probably my mistake? on my PDO? on my prepared statement? TIA
1)form action missing.
2)isset($_POST['login']) wrong name checking in if condition.
3)prepared statement have lots of issue.
try something like this
<?php
session_start();
//db connection
global $conn;
$servername = "localhost"; //host name
$username = "root"; //username
$password = ""; //password
$mysql_database = "userdb"; //database name
//mysqli prepared statement
$conn = mysqli_connect($servername, $username, $password) or die("Connection failed: " . mysqli_connect_error());
mysqli_select_db($conn,$mysql_database) or die("Opps some thing went wrong");
if(isset($_POST['submit']))
{
$username = $_POST['username'];
$password = $_POST['password'];
$stmt = $conn->prepare("SELECT * FROM tbl_account WHERE username =? AND password =? ");
$stmt->bind_param('ss',$username,$password);
$stmt->execute();
$get_result= $stmt->get_result();
$row_count= $get_result->num_rows;
$stmt->close();
$conn->close();
if ($row_count>0){
$_SESSION['username'] = $username;
header("location:index.php");
exit();
}else{
$error = "Your Login Name or Password is invalid";
}
}
?>
<html>
<head>
<title>Login</title>
</head>
<body>
<form action = "login.php" method = "POST">
<input type = "text" name="username"><br> //username
<input type = "password" name = "password"><br> //password
<input type = "submit" name = "submit" value = "Login"> /button
</form>
</body>
</html>
its syntax to use an exit(); after any header('location [...]') calls, you're missing this in your code which could be the reason why your page does nothing.
Also, I'd really like to touch up on some security notes: what the hell is that?
PDO has pre-written functions to allow you the full dynamics of a connection with security, they are there to be used; as it stands, your SQL statement is a security risk as you're directly inserting untrusted data into a statement without stripping it of injections.
Heres an example you could use to secure this:
class DB extends PDO
{
function __construct(
$dsn = 'mysql:host=localhost;dbname=kida',
$username = 'root',
$password = 'root'
) {
try {
parent::__construct($dsn, $username, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
parent::setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo $e->getMessage();
}
}
public function query($statement, array $parameters = array())
{
$stmp = parent::Prepare($statement);
$i = 1;
foreach($parameters as $parameter) {
$stmp->bindParam($i, $parameter);
$i++;
}
$stmp->execute();
return $stmp->FetchAll();
}
}
$Con = new DB();
$username = "example";
$row = $Con->query("SELECT * FROM table WHERE username = ?", [$username]);
You have wrongly used prepared statement.
You should write,
$query = $conn->prepare("SELECT COUNT('userID') FROM REGISTRY WHERE name = ? AND password' = ?");
$query->bindParam(':name', $username);
$query->bindParam(':password', $password);
$query->execute();
$result_rows = $query->fetchColumn(); // get result
Check this link for more detail.
Suggestion:- also add exit; after header tag to stop execution of afterward code.
try and change this code to
"SELECT COUNT('userID') FROM 'tbl_account' WHERE 'username' = '$username' AND 'password' = '$password' ");
put semicolon inside the quotes and on the outside as well
"SELECT userID FROM tab1_account WHERE username='$username' AND password='$password';";

0 concat displays first and last name but only first name is saved to mysql database

<?php
$servername = "localhost";
$username = "root";
$password = "";
$databasename = "test";
$conn = new mysqli($servername , $username , $password, $databasename);
$name = $_POST["firstname"];
$last = $_POST["lastname"];
$statement = mysqli_prepare($conn, "INSERT INTO user(firstname ,lastname) VALUES(?,?)");
mysqli_stmt_bind_param($statement ,"si", $name,$last);
mysqli_stmt_execute($statement);
$response = array();
$response["success"] = true;
echo json_encode($response);
?>
where is the problem in above php script that it save the first name in database while cannot save the lastname.
The problem is because of this line,
mysqli_stmt_bind_param($statement ,"si", $name,$last);
^ see here
It should be,
mysqli_stmt_bind_param($statement ,"ss", $name,$last);

Saving text from Textarea in mysql database with php (apostrophes)

html
<form id = "recall_TextArea2" method="post" action="SaveRecall2.php">
<center><textarea name="recall_Info" cols="60" rows="30em"></textarea></center>
</form>
php
if (isset($_POST['recall_Info'])) {
$recall_Info = $_POST['recall_Info'];
}
else {
echo "nothing was recalled.";
}
$recall_Info = stripslashes($recall_Info);
$recall_Info = mysqli_real_escape_string($recall_Info);
$update_sql = "UPDATE `participants` SET `recall_1` = '$recall_Info' WHERE `school_id` =825776 LIMIT 1 ;";
I want to be able to type in text in the text area that has apostrophes, but every time i try, it doesn't work.
It saves normal text (no apostrophes) when i take out
$recall_Info = stripslashes($recall_Info);
$recall_Info = mysqli_real_escape_string($recall_Info);
I'd say see if you are accessing your form/post data properly. Maybe echo out your form data before the sql to see what's going on.
This worked for me, I didn't change your sql query:
$username = "root";
$password = "root";
$host = "localhost";
$dbname = "test";
$mysqli = new mysqli($host, $username, $password, $dbname);
$recall_Info ="this is new recall info text";
$update_sql = "UPDATE `participants` SET `recall_1` = '$recall_Info' '' WHERE `school_id` ='825776' LIMIT 1;";
$stmt = $mysqli->stmt_init();
$stmt->prepare($update_sql);
$stmt->execute();
if ($stmt->affected_rows > 0) {
$OK = true;
}
if ($OK) {
echo 'update successful';
}

Categories