if/else statement in function php not inserting [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 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.

Related

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']."',
'')");

num_rows doesn't work with prepared statement [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 have a test code where I try to reach my database information. But one script that uses prepared statements does not work, and second without prepared statements works just fine.
$userzzz = "test";
With this script, I get "BAD" as the result
$db = new mysqli("localhost", "root", "", "test");
$stmt = $db->prepare('SELECT * FROM user WHERE username=?');
$stmt->bind_param('s', $userzzz);
$stmt->execute();
echo $stmt->num_rows();
if ($stmt->num_rows > 0){
echo "good";
} else {
echo "bad";
}
From the manual,
The use of mysqli_stmt_num_rows() depends on whether or not you used mysqli_stmt_store_result() to buffer the entire result set in the statement handle.
If you use mysqli_stmt_store_result(), mysqli_stmt_num_rows() may be called immediately.
Which means that you'll have to use $stmt->store_result(); after executing, but before accessing the num_rows property.
$stmt = $db->prepare('SELECT * FROM user WHERE username=?');
$stmt->bind_param('s', $userzzz);
$stmt->execute();
$stmt->store_result();
echo $stmt->num_rows;
if ($stmt->num_rows > 0){
echo "good";
} else {
echo "bad";
}
If you don't do this, the rows won't be buffered into the memory, and there's no way of knowing how many rows actually was returned, until you loop through the entire set of data (by while ($stmt->fetch())).
PHP.net on mysqli_stmt_store_result()
in object oriented mysqli, num_rows is not a function, it's an attribute of the result (stmt). You need $stmt->num_rows; not $stmt->num_rows();
In your second example, you're not using (), you are doing it correctly, hence why it functions in the second but not the first.
$db = new mysqli("localhost", "root", "", "test");
$stmt = $db->prepare('SELECT unique_col FROM user WHERE username=?');
$stmt->bind_param('s', $userzzz);
$stmt->execute();
$stmt->store_result();
$rows = $stmt->num_rows;
if ($rows > 0){
echo "good";
} else {
echo "bad";
}
I also added $stmt->store_result(). It is finicky and num_rows will be 0 unless you store the result before you run $stmt->num_rows;
I'd also use a unique column instead of *, such as id for example.
Well you need to bind the results after you execute, this will work in your case (works for me):
<?php
$userzzz = 'test';
$db = new mysqli("localhost", "root", "", "test");
$stmt = $db->prepare('SELECT * FROM users WHERE username = ?');
$stmt->bind_param('s', $userzzz);
$stmt->execute();
$stmt->store_result();
echo $stmt->num_rows();
if ($stmt->num_rows() > 0){
echo "good";
} else {
echo "bad";
}
?>

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.

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