Unexpected catch error in code [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 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

Related

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.

Fail input to database mysql [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 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']."',
'')");

Php and mysql weird error with select [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 6 years ago.
Improve this question
I'm a beginner in web design and I have this problem. I'm trying to create a login page but when I try to create the login it throws a error as follows:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ':username and passwordhash=:passwordhashed)' at line 1
With php code of
Try {
// $SQL = 'INSERT INTO Passwords (username, password, passwordhashed) VALUES (:username,:password,:passwordhashed);';
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
$PasswordHashed = sha1($password);
echo "Username: ". $username ."<br> Password: ". $password . "<br> PasswordHashed: " . $PasswordHashed;
$SQL = null;
$SQL = "SELECT * FROM BlaBla WHERE (username=:username and passwordhash=:passwordhashed);";
$Statement = $MySQL->prepare($SQL);
$Statement->bindValue(':username', $username);
$Statement->bindValue(':passwordhashed', $PasswordHashed);
$Statement->execute();
$Statement = $MySQL->query($SQL);
if ($Statement->rowCount() < 1 ) {
echo 'NOPE';
} else {
echo 'welcome back '. $username;
}
} catch(PDOException $e) {
$ErrorTitle = 'Error';
$Error = "error writing to database";
$ErrorInfo = '<p>Please contact administrator at stephan.littel#stecasso.nl</p> <br> <p>'. $e->getMessage() . '</p>';
include './HTML/Error.php';
exit();
}
I don't know what the error is. Could anyone help me?
Here:
$Statement = $MySQL->prepare($SQL);
^---your prepared statement
$Statement->bindValue(':username', $username);
$Statement->bindValue(':passwordhashed', $PasswordHashed);
$Statement->execute();
$Statement = $MySQL->query($SQL);
^----raw queries have no placeholders
You prepare a statement, and execute it. But then you do a RAW query with the same SQL, replacing the result of the prepared version. You cannot use placeholders in a raw query like that. Hence your error.
That final ->query() call is useless and redundant.
Found the problem. Problem was I used query and execute. My fault of slopy bug tracking.

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";
}

Parse Error: (T_ENCAPSED_AND_WHITESPACE) [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
include 'connect.php';
if ($stmt = $mysqli->prepare("INSERT users (user_name, user_pass) VALUES (mysql_real_escape_string ($_POST['user_name'], sha1($_POST['user_pass']"))
{
$stmt->bind_param("ss", $user_name, $user_pass);
$stmt->execute();
$stmt->close();
}
I get this error on the line of code above, I've been staring at it for ages but can't figure out what's wrong. I'm new to PHP, MySQL and HTML. Please help me.
Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in C:\xampp\htdocs\signup.php on line 77
The good thing is you are trying to prepare, the bad news is you doing it wrong:
$username = $_POST['user_name'];
$password = $_POST['user_pass'];
$query = "INSERT users (user_name, user_pass) VALUES (?, sha1(?)) ";
/* create a prepared statement */
if ($stmt = $mysqli->prepare($query)) {
/* bind parameters for markers */
$stmt->bind_param("ss", $username, $password);
/* execute query */
$stmt->execute();
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
issues:
mysql_real_escape_string is deprecated
mysqli_real_escape_string would be useless
Your string concatenation is wrong

Categories