Fail input to database mysql [closed] - php

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I Want to ask about input data to database.
<?php
include "koneksi.php";
if(isset($_POST['daftar'])){
$daftar = mysqli_query($conn, "INSERT INTO tb_daftar VALUES
('".$_POST['id']."',
'".$_POST['nama']."',
'".$_POST['asal_sekolah']."',
'".$_POST['jenis_kelamin']."',
'".$_POST['nama_ayah']."',
'".$_POST['nama_ibu']."',
'".$_POST['alamat']."',
'".$_POST['no_hp']."',
'')");
if($daftar){
$pesan1 = "Berhasil daftar";
echo "<script type='text/javascript'>alert('$pesan1');</script>";
}else{
$pesan2 = "Gagal daftar";
echo "<script type='text/javascript'>alert('$pesan2');</script>";
}
}
?>
That result always show " Gagal daftar "..
How to fix it? Thanks!

You have an extra comma after the last value. You should also use a prepared statement to prevent SQL injection.
if ($dafter = mysqli_prepare($conn, "INSERT INTO tb_dafter VALUES (?, ?, ?, ?, ?, ?, ?, ?)")) {
mysqli_stmt_bind_param($dafter, "ssssssss", $_POST['id'], $_POST['nama'], $_POST['asal_sekolah'], $_POST['jenis_kelamin'], $_POST['nama_ayah'], $_POST['nama_ibu'], $_POST['alamat'], $_POST['no_hp']);
mysqli_stmt_execute($dafter);
$pesan1 = "Berhasil daftar";
echo "<script type='text/javascript'>alert('$pesan1');</script>";
} else {
$pesan2 = htmlentities(mysqli_error($conn));
echo "<script type='text/javascript'>alert('$pesan2');</script>";
}

Your code is not in good condition, You need to think in many aspect like,
Integer value like id will not be in quotes.
Sequence matter if you not provided column names with table name, Highly risky without column name.
You query is easy to Inject, SQL Injection
You have not check $_POST variable value, with isset, Check my other answer about this
To cover your risk use mysqli or pdo
But I suggest to insert use mysqli or pdo. Here are some link to learn about mysqli:
mysqli_prepare
mysqli_stmt_bind_param
Prepared Statements in MySQLi

View errors from mysql query using mysqli_error
else{
$pesan2 = mysqli_error($conn);
echo "<script type='text/javascript'>alert('Error: '+$pesan2);</script>";
}

$daftar = mysqli_query($conn, "INSERT INTO tb_daftar((database columns))
VALUES
('".$_POST['id']."',
'".$_POST['nama']."',
'".$_POST['asal_sekolah']."',
'".$_POST['jenis_kelamin']."',
'".$_POST['nama_ayah']."',
'".$_POST['nama_ibu']."',
'".$_POST['alamat']."',
'".$_POST['no_hp']."',
'')");

Related

Unable to insert into two different tables with help of transactions [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
Below is a my code write up in which i am trying to insert data into two different tables with help of transactions but code is not executing. Trying very hard to find out issue but unable to resolve it.
I am getting this error: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''u_id_fk','device_type','ip_num','package','pkg_id_fk') VALUES('79','abc','128.1' at line 1[]
$cust_name = 'multi';
$u_name = 'multi2';
$cnic_num = '421';
$address = 'sadaddd';
$password = md5('423423');
$cellnum='43243';
$p_id_fk=(int)'3';
try {
// First of all, let's begin a transaction
$conn->beginTransaction();
// If we arrive here, it means that no exception was thrown
// i.e. no query has failed, and we can commit the transaction
// Forgot to close the VALUES bracket and couldn't find your $email
$users_stmt=$conn->prepare("INSERT INTO users (`cust_name`, `u_name`, `cnic`, `address`, `password`, `email`) VALUES (:cust_name, :u_name, :cnic, :address, :password, :email)");
// PDO::execute() can accept an array of parameter bound to your query so you may avoid selecting data type when using bindParam()
$users_stmt->execute(["cust_name"=>$cust_name, "u_name"=>$u_name, "cnic"=>$cnic_num, "address"=>$address, "password"=>$password, "email"=>$email]);
// Not sure if $db is a PDO object...
$connections_stmt=$conn->prepare("INSERT INTO connections('u_id_fk','device_type','ip_num','package','pkg_id_fk') VALUES(:u_id_fk,:device_type,:ip_num,:package,:pkg_id_fk)");
$connections_stmt->execute(["u_id_fk"=>$u_id,"device_type"=>$device_type,"ip_num"=>$ip_num,"package"=>$package,"pkg_id_fk"=>$p_id_fk]);
$conn->commit();
} catch (Exception $e)
{
// An exception has been thrown
// We must rollback the transaction
$conn->rollback();
echo $e;
}
Please help to resolve it! Thanks
It is very important to set PDO error mode to EXCEPTION during connection.
Avoid using simple hashing algorithms for password as it can be extracted using Rainbow Attack.
$cust_name = 'multi';
$u_name = 'multi2';
$cnic_num = '421';
$address = 'sadaddd';
$password = md5('423423');
$cellnum='43243';
$p_id_fk=(int)'3';
try {
// DB vars
$db_host="";
$db_name="";
$db_username="";
$db_password="";
// Create a new PDO connection and set error mode to EXCEPTION
$conn=new PDO("mysql:host=".$db_host.";dbname=".$db_name,$db_username,$db_password,array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$conn->beginTransaction();
// Forgot to close the VALUES bracket and couldn't find your $email
$users_stmt=$conn->prepare("INSERT INTO users (`cust_name`, `u_name`, `cnic`, `address`, `password`, `email`) VALUES (:cust_name, :u_name, :cnic, :address, :password, :email)");
// PDO::execute() can accept an array of parameter bound to your query so you may avoid selecting data type when using bindParam()
$users_stmt->execute(["cust_name"=>$cust_name, "u_name"=>$u_name, "cnic"=>$cnic_num, "address"=>$address, "password"=>$password, "email"=>$email]);
$connections_stmt=$conn->prepare("INSERT INTO connections(`u_id_fk`,`device_type`,`ip_num`,`package`,`pkg_id_fk`) VALUES(:u_id_fk, :device_type, :ip_num, :package, :pkg_id_fk)");
$connections_stmt->execute(["u_id_fk"=>$u_id, "device_type"=>$device_type, "ip_num"=>$ip_num, "package"=>$package, "pkg_id_fk"=>$p_id_fk]);
$conn->commit();
} catch (Exception $e){
$conn->rollback();
echo $e->getMessage();
}
The closing double quotation in your first statement is not correct, it must be at the end of it and also you missed the end bracket of prepare function
$stmt=$conn->prepare("INSERT INTO users (cust_name, u_name,cnic,address,password,email) VALUES (?, ?, ?, ?, ?, ?)");
Try to correct that typo.

if/else statement in function php not inserting [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
what i want to do is that it checks the input field and after that it will insert the following query or it it gives an error message. My problem is that my query won't insert.
My PHP function that won't work (other file then html file):
function Code($userID) {
require '../conn.php';
$sql = "SELECT `current_uses` FROM `sub_codes` WHERE `content` = '".$_POST['Code']."'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result);
if ($row['current_uses'] > 0){
$query = "INSERT INTO `partner_subscriptions` (`id`, `user_id`, `sub_id`, `allowed_users`, `start_date`, `end_date`) VALUES (NULL, ?, ?, ?, ?, ?);";
$stmt = $conn->prepare($query);
$_userID = $userID;
$_subID = '99';
$_allowedUsers = '100';
$_startDate = date('Y-m-d');
$sql2 = "SELECT `end_date` FROM `sub_codes` WHERE `content` = '".$_POST['Code']."'";
$result2 = mysqli_query($conn, $sql2);
$row2 = mysqli_fetch_array($result2);
$_endDate = $row2['end_date'];
$stmt->bind_param("sssiiii", $_userID, $_subID, $_allowedUsers, $_startDate, $_endDate);
$stmt->execute();
$lastID = $conn->insert_id;
$stmt->close();
return $lastID;
}else {
echo "Wrong code";
}
}
My html file:
<br/><div class="form-group">
<label title="Required">Free description code:</label>
<input type="text" name="Code" class="form-control" id="Code"/>
</div><br/>
The rest of my PHP file (that i think you need to know):
if (usedmail($_POST['username'])==true) {
$lastID = saveUser($_POST['fnln'], $_POST['username'], password_hash($_POST['password'], PASSWORD_BCRYPT), 0, 0, 1);
$niv = NULL;
if ($_POST['type'] == "3") { // If the partner is an educational institution look for niveau
$niv = NivID($_POST['niv']);
}
Code($lastID, $_POST['Code']);
$path = saveImage();
Contact($lastID);
Image($lastID);
Social($lastID);
Story($lastID);
Skill($lastID);
$orgID = saveOrganisation($lastID, $_POST['organisation'], $path, $_POST['type'], $_POST['branche'], $niv);
updateUser($orgID, $lastID);
}
else {
header('Location: ../../mailerror');
}
every other function works normal except the code function and i don't really know why. I appreciate your help!
Well, for explanation reasons how to use mysqli the right way. First of all, you have to keep control of your code. Always check what happens and catch any mistakes. You don 't do that and that 's the reason you don 't know, why your insert statement is not executed.
Error Handling for the win!
Use the results, which are explained in detail in the manual. Nearly every mysqli method returns a false value, when something went wront. Use it!
$sql = "SELECT current_uses FROM sub_codes WHERE content = ?";
$stmt = mysqli_prepare($connection, $sql);
// Is there a prepared statement?
if (!$stmt) {
die(printf('Something went wrong: %s.', mysqli_error($connection)));
}
// use the mysqli statement (one type definition per used variable)
$result = mysqli_stmt_bind_param($stmt, "s", $_POST['code']);
if (!$result) {
die(printf('Something went wrong: %s.', mysqli_stmt_error($stmt)));
}
// execute the statement
$result = mysqli_stmt_execute($stmt);
if (!$result) {
die(printf('Something went wrong: %s.', mysqli_stmt_error($stmt)));
}
As you can see it is necessary to check what the result of each mysqli function call is to avoid unpredictable behavior of your script. Always keep in mind not to use post variables directly in sql statements. This is a huge mistake and opens your script for several vulnerabilities via sql injection.
Please read one of the many sql injection topics here on stack overflow to understand what sql injection is and how you can prevent it: How can I prevent SQL injection in PHP?
I had to change "sssiiii" to "iiiss" because Every single character of your 'sssiiii' stands for a single value that is bound to the statement.

Php and mysql insert [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I have the next code, but it inserts two rows in the mysql database instead of one. Could ypu please take a look to the code?
Regards.
<?php
$name= $_POST['name'];
$password = $_POST['password'];
mysql_connect("localhost","username","mypass");
mysql_select_db("databaseName");
mysql_query($query ="insert into users(name,password) values ('$name','$password')");
if (mysql_query($query) === TRUE) {
echo "Record saved";
} else {
echo "Error";
}
?>
Don't call mysql_query() when you assign the $query variable. And remember to escape your data, since you're not using prepared statements.
mysql_connect("localhost","username","mypass");
$name = mysql_real_escape_string($_POST['name']);
$password = mysql_real_escape_string($_POST['password']);
$query ="insert into users(name,password) values ('$name','$password')";
if (mysql_query($query)) {
echo "Record saved";
} else {
echo "Error: " . mysql_error();
}
Dont use the mysql_query function twice,
you want to check it in if statement, then dont call it before if clause.
See this following code.
$query ="insert into users(name,password) values ('$name','$password')"
if (mysql_query($query) === TRUE) {
echo "Record saved";
} else {
echo "Error";
}

Unexpected catch error in code [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm doing registration in PHP and I am stuck on an unexpected catch, can you help me please?
if (isset($_POST['nick']) && isset($_POST['heslo']) &&
isset($_POST['email']) && isset($_POST['datnar']))
{
try
{
$email = ($_POST['email']);
$datnar = ($_POST['datnar']);
$nick = ($_POST['nick']);
$heslo = md5($_POST['heslo']);
$db->query("INSERT INTO tblosoba(`nick`, `heslo`, `email`, `datnar`) VALUES ($nick, '$heslo', $email, $datnar)");
echo "Registrace dokončena.";
catch( PDOException $Exception ) {
echo "Uživatel existuje";
}
}
You need to close the try block.
{
try
{
$email = ($_POST['email']);
$datnar = ($_POST['datnar']);
$nick = ($_POST['nick']);
$heslo = md5($_POST['heslo']);
$db->query("INSERT INTO tblosoba(`nick`, `heslo`, `email`, `datnar`) VALUES ($nick, '$heslo', $email, $datnar)");
echo "Registrace dokončena.";
} //<-------------------------------------------- Here
catch(PDOException $Exception ) {
echo "Uživatel existuje";
}
}
Warning : Your code is vulnerable to SQL Injection. You need to filter the $_POST values before passing it to your query.
Use Prepared Statements (Parametrized Queries) to ward off SQL Injection attacks as you are already using PDO.
Add a closing curly bracket (}) before the catch
Here is how to fix your code
if (isset($_POST['nick']) && isset($_POST['heslo']) &&
isset($_POST['email']) && isset($_POST['datnar']))
{
$sql = "INSERT INTO tblosoba(`nick`, `heslo`, `email`, `datnar`) VALUES (?,?,?,?)";
$data = [$_POST['nick'],$_POST['heslo'],$_POST['email'],$_POST['datnar']];
$db->prepare($sql)->execute($data);
echo "Registrace dokončena.";
}
Note that you should not use try-catch here but should use prepared statement instead

i have an error while inserting the values what i did [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
help me with this code i am new to php
<?php
$conn=mysql_connect("localhost","root","","test");
if(isset($_POST['submit']))
{
$sql="INSERT INTO registration(fname,designation,emailid,
address,phonenumber)VALUES('".$_POST['fname']."','".$_POST['designation']."','".$_POST['ema
lid']."', '".$_POST['address']."','".$_POST['phonenumber']."')";
echo $sql;
$result=mysql_query($conn,$sql);
echo $result;
}
else{
echo "Error";
}
?>
its a registration page getting values and inserting it in the table...
You have the parameters around the wrong way here:
$result=mysql_query($conn,$sql);
Try
$result=mysql_query($sql, $conn) or die(mysql_error($conn));
Side notes:
Don't use mysql_*() functions: they're deprecated. Use mysqli_*() versions instead.
You should escape your user inputs with mysql_real_escape_string() to protect against SQL Injection attacks. Consider using prepared statements with mysqli_() instead.
Take a look at this link which is a good tutorial for inserting data (from a form etc.) to a mysql database.
Also: be aware of sql-injection and prevent it. here is a tutorial on how to do this: link
If you want to have readable code, set the $_POST[] values to a variable, and then pass them to the query, it's not different in fact but this is more easy and clean.:
<?php
$conn=mysql_connect("localhost","root","","test");
if(isset($_POST['submit']))
{
$fname = $_POST['fname'];
$designation = $_POST['designation'];
$emailid = $_POST['emailid'];
$address = $_POST['address'];
$phonenumber = $_POST['phonenumber'];
$sql="INSERT INTO registration(fname,designation,emailid,address,phonenumber)";
$sql .="VALUES('$fname', '$designation', '$emailid', '$address', '$phonenumber')";
echo $sql;
$result=mysql_query($conn,$sql);
echo $result;
}
else{
echo "Error";
}
?>
you hade a typing mistake in $_POST['emailid']...
and you can select your database with this:
mysql_select_db('your db name');
put this line after your connection variable means $conn
and this is wrong:
$result = mysql_query ($conn, $sql)
you have to set the query first:
$result = mysql_query($sql, $conn)

Categories