Inserting a statement requiring minimum number of characters - php

Here I have a code which inserts data into db. It's working fine now, but I want the title to have a minimum of 4 characters and the body a minimum of 500.
Here is my code:
<?php
if(isset($_POST['submit'])) {
//get blog data
$title=strip_tags($_POST['title']);
$body=strip_tags($_POST['body']);
$posted_by = $first_name;
$category=$_POST['category'];
$bio = $bio;
$userid=$_COOKIE['user'];
$date = date ('d-M-Y');
if ($title && $body && $category) {
$query = "INSERT INTO blogs (userid, title, body, posted_by, bio, category_id, posted) VALUES ('$userid', '$title', '$body', '$posted_by','$bio', '$category', '$date')";
$run = mysqli_query($con,$query);
if($query) {
echo "posted";
}
else {
echo "error";
}
}else {
echo "data missing";
}
}
?>
I tried the code below to put minimum requirements for the title and body, but it echoes the title error message whenever you submit data even when the title contains more than 5 characters.
<?php
if(isset($_POST['submit'])) {
//get blog data
$title=strip_tags($_POST['title']);
$body=strip_tags($_POST['body']);
$posted_by = $first_name;
$category=$_POST['category'];
$bio = $bio;
$userid=$_COOKIE['user'];
$date = date ('d-M-Y');
if (strlen($title<5)) {
echo "Title must be of minimum 5 characters";
}
else {
if (strlen($body<500)) {
echo "Title must be of minimum 500 characters";
}
else {
$query = "INSERT INTO blogs (userid, title, body, posted_by, bio, category_id, posted) VALUES ('$userid', '$title', '$body', '$posted_by','$bio', '$category', '$date')";
$run = mysqli_query($con,$query);
if($query) {
echo "posted";
}
else {
echo "error";
}
}
}
}
?>

A question as such deserves an explanation for future readers to the question.
The reason why your code is failing, is that:
if (strlen($title<5))
evaluates to:
function($string conditional)
when the syntax is:
function($string) conditional
The manual states:
int strlen ( string $string )
http://php.net/manual/en/function.strlen.php
Example pulled from the manual:
if (strlen($foo) === 0) echo 'Null length is Zero <br>';
Plus, as stated in comments. Your query is subject to an SQL injection. It's best to use a prepared statement.
Consult the following links:
How can I prevent SQL injection in PHP?
https://en.wikipedia.org/wiki/Prepared_statement

I think the issue lies with the conditions you used.
if (strlen($title<5))
should be
if (strlen($title)<5)
similarly
if (strlen($body<500))
to be
if (strlen($body)<500)

Try this:
<?php
if(isset($_POST['submit'])) {
//get blog data
$title=strip_tags($_POST['title']);
$body=strip_tags($_POST['body']);
$posted_by = $first_name;
$category=$_POST['category'];
$bio = $bio;
$userid=$_COOKIE['user'];
$date = date ('d-M-Y');
if (strlen($title) < 5) {
echo "Title must be of minimum 5 characters";
}else {
if (strlen($body) <500 ) {
echo "Body must be of minimum 500 characters";
}else {
$query = "INSERT INTO blogs (userid, title, body, posted_by, bio, category_id, posted) VALUES ('$userid', '$title', '$body', '$posted_by','$bio', '$category', '$date')";
$run = mysqli_query($con,$query);
if($query) {
echo "posted";
}else {
echo "error";
}
}
}
}
?>

Related

PHP Form Posts to MySQL Database Successfully, But Adds Blank Rows sometimes when registering

PHP Form Posts to MySQL Database Successfully, But Adds Blank Rows sometimes when registering.
here is my code:
include("includes/db.php");
if (isset($_POST['submit']) && $hidden == "" ) {
$product = mysqli_real_escape_string($bd, $_POST['product']);
$name = mysqli_real_escape_string($bd, $_POST['name']);
$address = mysqli_real_escape_string($bd, $_POST['address']);
$coupon = mysqli_real_escape_string($bd, $_POST['coupon']);
date_default_timezone_set("Asia/Kolkata");
$dates = date('Y-m-d H:i:s');
if (isset($_FILES["invoice_copy"]["name"])) {
$imgpancard = $_FILES["invoice_copy"]["name"];
$tmp_name = $_FILES['invoice_copy']['tmp_name'];
$error = $_FILES['invoice_copy']['error'];
if (!empty($imgpancard)) {
$location = 'doc/';
if (move_uploaded_file($tmp_name, $location.$imgpancard)){
//echo 'Uploaded';
}
}
}
$query = mysqli_query($bd, "SELECT * FROM customer WHERE coupon='".$coupon."'");
if(mysqli_num_rows($query) > 0) {
echo'<script> alert("COUPON ALEARDY EXISTS!");
window.location="register.php";
</script> ';
}
else {
$sql = "INSERT INTO customer (product, customer_name, address, coupon, RegistrationDate, invoice_copy) VALUES ('$product', '$name', '$address', '$coupon', '$dates', '$imgpancard')";
if(mysqli_query($bd, $sql)){
echo'<script> alert("DATA SUBMITTED SUCCESFULLY!");
window.location="index.html"; </script> ';
}
else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($bd);
}
}
}
how to of 10 times one times blank data is inserted.how to avoid it can please tell me , whether code is wrong or not. In every input feild i have used required attribute

MySQL query insert success but return false

the problem is..i try to parsing json from php..here is jquery code:
$.post( "confirmsignup.php", $("#signupform").serialize()).always(function( data ) {
alert(data.msg);
}, "json");
PHP code:
if (isset($_POST['gender'])&&isset($_POST['fname'])&&isset($_POST['sname'])&&isset($_POST['username'])&&isset($_POST['dob'])) {
$gender=secureing($_POST['gender']);
$fname=secureing($_POST['fname']);
$sname=secureing($_POST['sname']);
$username=secureing($_POST['username']);
$email=secureing($_POST['email']);
$dob=secureing($_POST['dob']);
if (isset($_POST['agree'])&&isset($_POST['pass'])&&isset($_POST['repass'])) {
$pass=secureing($_POST['pass']);
if ($_POST['pass']==secureing($_POST['repass'])) {
$query = "INSERT INTO users VALUES('$username', '$gender', '$fname', '$sname', '$email', '".md5($pass)."', '$dob')";
if(!($query_run = mysql_query($query))){
$msg = "error";
}else{
$msg = "complete";
}
}
}
}
header('Content-Type: application/json');
?>
{
"msg": "<?php echo $msg ." - ". $query; ?>"
}
secureing() is for returning string after escape_string..
$msg suppose to return string "complete"... but it returning "error"..
however in phpmyadmin, query is successfully executed..
i think there is no mistake..what is my mistake?please help..
Can you please change the following code with your code, I have used mysql_insert_id to check record is inserted or not.
$query = "INSERT INTO users VALUES('$username', '$gender', '$fname', '$sname', '$email', '".md5($pass)."', '$dob')";
$query_run = mysql_query($query);
$id = mysql_insert_id();
if($id > 0)
{
$msg = "complete";
}
else
{
$msg = "error";
}
It may help you.
I have same issue long time ago!
it's because you haven't any AI primary key in the table!
add a field like this to the table: id INT Primary Key Auto Increment.
this will works!
and migrate to mysqli or pdo for better security and support! ;)
try my code is seem you have put wrong condition
if (isset($_POST['gender'])&&isset($_POST['fname'])&&isset($_POST['sname'])&&isset($_POST['username'])&&isset($_POST['dob'])) {
$gender=secureing($_POST['gender']);
$fname=secureing($_POST['fname']);
$sname=secureing($_POST['sname']);
$username=secureing($_POST['username']);
$email=secureing($_POST['email']);
$dob=secureing($_POST['dob']);
if (isset($_POST['agree'])&&isset($_POST['pass'])&&isset($_POST['repass'])) {
$pass=secureing($_POST['pass']);
if ($_POST['pass']==secureing($_POST['repass'])) {
$query = "INSERT INTO users VALUES('$username', '$gender', '$fname', '$sname', '$email', '".md5($pass)."', '$dob')";
if(!(mysql_query($query))){
$msg = "error";
}else{
$msg = "complete";
}
}
}
}
i just found the solution, after change my php API to connecting to database.
from:
if(!#mysql_connect('localhost', 'root', '')||!#mysql_select_db('knewit')){
die("something not right");
}
to:
$mysqli = new mysqli("localhost", "root", "", "knewit");
after that, i change my executing method from mysql_query to $mysqli->query.
i also change my jquery post method from always to done.
and the final code be like this.
jQuery script:
$.post( "confirmsignup.php", $("#signupform").serialize()).done(function( data ) {
alert(data.msg);
}, "json");
PHP script:
if (isset($_POST['agree'])&&isset($_POST['pass'])&&isset($_POST['repass'])) {
$passs=secureing($_POST['pass']);
if ($_POST['pass']==secureing($_POST['repass'])) {
$query = "INSERT INTO users VALUES('$username', '$gender', '$fname', '$sname', '$email', '$passs', '$dob')";
if(!($query_run = $mysqli->query($query))){
$msg = "error";
}
else
{
$msg = "complete";
}
}
}
}
header('Content-Type: application/json');
$arrayName = array('msg' => $msg );
echo json_encode($arrayName);
thank you for answer my question. i really appreciate it.

inserting data into 2 tables at once

I am wondering how can I insert the values retrieved from a HTML form into 2 tables, loginDetails and memberDetails.
loginDetails (table_1 shown in the code)
loginID (PK) <-- auto increment
username
password
memberDetails (table_2 shown in the code)
memberID (PK) <-- auto increment
loginID (FK)
These are the codes I have so far, however the loginID in memberDetails table are always 0,:
PHP codes
$Query = "INSERT INTO $table_1 VALUES (NULL,
'".$formValue['username']."',
'".$formValue['password']."')";
if (mysqli_query($Link, $Query)) {
$lastID = mysql_insert_id();
$Query2 = "INSERT INTO $table_2 VALUES (NULL,
'".$lastID."')";
if (mysqli_query($Link, $Query2)) {
$message = "You've sucessfully created the account!";
echo json_encode(array('success'=>'true', 'action'=>'login','html'=>$message, 'console.log'=>$Query));
}
else {
$message = "Error occur in query2";
echo json_encode(array('action'=>'error','html'=>$message, 'console.log'=>$Query));
}
}
else {
$message = "Error in query1";
echo json_encode(array('action'=>'error','html'=>$message, 'console.log'=>$Query));
}
It would be great if this question can be solved, as i have been struggling in this for 3 nights already. Cheers.
You can place your queries in an array. Loop through the array. If an error occurs, exit the script.
$myQueries = array(`"INSERT INTO $table_1 VALUES (NULL,
'".$formValue['username'].",
'".$formValue['password']."')",
"INSERT INTO $table_2 VALUES (NULL,
'".$lastID."')"
)`;
for($i = 0; $i < count($myQueries); $i++){
if (mysqli_query($Link, $myQueries[$i])) {
$lastID = mysql_insert_id();
$message = "You've sucessfully created the account!";
echo json_encode(array('success'=>'true',
'action'=>'login',
'html'=>$message,
'console.log'=>$Query));
}
else {
$message = "Error occur in query[$i]";
echo json_encode(array('action'=>'error',
'html'=>$message,
'console.log'=>$Query));
exit; // stops the next query
}
}
}

Notice: Undefined variable: title in E:\xampp\htdocs\blog4\new-post.php on line 11

Notice: Undefined variable: title in E:\xampp\htdocs\blog4\new-post.php on line 11
I keep getting this error and also Missing data is appearing before any data is submitted
include('db.php');
if(isset($_POST['submit'])){
$title = $_POST['title'];
$body = $_POST['body'];
}
if($title && $body){
$query = mysql_query("INSERT INTO posts (title, body) VALUES('$title', '$body')");
if($query){
echo"Post Added";
}else{
echo"error";}
}else{
echo"Missing data";
}
db.php:
<?php
$db = new PDO('mysql:host=127.0.0.1;dbname=db_name_here', 'username', 'password');
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
?>
new-post.php:
<?php
include 'db.php';
if(isset($_POST['submit'])) {
$query = $db->prepare('INSERT INTO posts (title, body) VALUES (?, ?)');
$result = $query->execute(array($_POST['title'], $_POST['body']));
if($result) {
echo 'Post Added!';
} else {
echo 'Database error.';
}
} else {
echo 'Missing data!';
}
?>
Please don't use mysql_* functions, they are no longer maintained and are in the deprecation process.
Use PDO instead.
PDO also supports prepared statements, which helps avoid SQL injection.
If $_POST['submit'] is not set, $title will not be initialized.
Substitute with
if (isset($title, $body)) {
//....
Initialized the $title with empty like this at the top
$title = "";
Check for a POST request then check and set your values; If values are not null then do your query, also make your inputs safe else having ' in your data will cause an error.
include('db.php');
if($_SERVER['REQUEST_METHOD']=='POST'){
$title = (!empty($_POST['title'])?$_POST['title']:null);
$body = (!empty($_POST['body'])?$_POST['body']:null);
if($title != null && $body != null){
$query = mysql_query("INSERT INTO posts (title, body) VALUES ('".mysql_real_escape_string($title)."', '".mysql_real_escape_string($body)."')");
if($query){
$result = "Post Added";
}else{
$result = "Error";
}
}else{
$result = "Missing data";
}
echo $result;
}

PHP query inserts 2 rows into the table

OK, here is the deal. I have 3 queries putting data in different tables. 2 of them are in included files. I've tried to put them into the main code, the result was the same. The first two queries inserts one row with the data and a blank row. The third works fine. Here is the code.
This in the main page:
<? $p=0;
if ($select2)
{
$event=$select2;
}
else
{
require_once("insert_gal_name.php5");
}
if ($select)
{
$folder=$select;
}
else
{
require_once("insert_folder.php5");
if (file_exists("Connections/".$folder))
{
}
else
{
mkdir("Connections/$folder",0777);
}
}
while($p<$number)
{
$p++;
$dir = 'Connections/'.$folder.'/'; // Директорията в която ще се записват файловете
copy($_FILES['file']['tmp_name'][$p],"$dir".$_FILES['file']['name'][$p]); //Копиране на файла
echo "Файлът бе качен успешно!<br>"; // Извеждане на съобщение показващо, че файла е качен
if($_FILES['file']['name'][$p])
{
$real_file_name = $dif_of_files.$_FILES['file']['name'][$p];
$nom_file = str_replace(" ", "", $real_file_name); }
$query = "INSERT INTO gallery (name, title, day, month, year) VALUES ('$nom_file', '$event', '$day', '$month', '$year')";
$result = mysql_query($query) or die(mysql_error());
}
if (!$result)
{
echo "Error";
}
else
{
echo "All data was uploaded successfuly.";
}
?>
And here are the includes in the order they are placed in the source
<? $query = "INSERT INTO gallery_names (name) VALUES ('$event')";
$result = mysql_query($query) or die(mysql_error());
if (!$result)
{
echo "Error";
}
else
{
echo "The gallery was created successfuly.";
}
?>
<? $query = "INSERT INTO folders (name) VALUES ('$folder')";
$result = mysql_query($query) or die(mysql_error());
if (!$result)
{
echo "Error";
}
else
{
echo "The folder was created successfuly.";
}
?>
<?
if($event!='')
{
$query1 = "INSERT INTO gallery_names (name) VALUES ('$event')";
$result1 = mysql_query($query1) or die(mysql_error());
if (!$result1)
{
echo "Error";
}
else
{
echo "The gallery was created successfuly.";
}
}
?>
If $select2 is false then this code will do two inserts. If $event is empty one of these will be an empty row which sounds like the problem you're having.
What are the values of $select2 and $event? Have you tried debugging them?

Categories