Php and mysql weird error with select [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 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.

Related

Error while add data in database SQL Server 2016 [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
Currently, I have one table in my database called 'factory'. In this table, there are two columns, 'Fac_ID' and 'Fac_Name'. Now, I want to create a function to add some new factory to the table 'factory'.
The value of 'Fac_ID' and 'Fac_Name' must be same, which mean when I want to add factory 'F09', the value of Fac_ID and Fac_Name must be same which is 'F09'.
When I used to connect with MYSQL database (PDO), the addition is successful. BUt when i change to MSSQL (PDO),
" Uncaught PDOException: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined in C:\xampp\htdocs\ebooking\add_factory.php:24 Stack trace: #0 C:\xampp\htdocs\ebooking\add_factory.php(24): PDOStatement->bindParam(':Fac_ID', 'F11')"
Here is my code for add_factory.php
<?php
require_once "configPDO.php";
if(isset($_POST['Submit'])) {
$Fac_ID = $_POST['Fac_ID'];
// checking empty fields
if(empty($Fac_ID)) {
if(empty($Fac_ID)) {
echo "<font color='red'>Name field is empty.</font><br/>";
}
//link to the previous page
echo "<br/><a href='javascript:self.history.back();'>Go Back</a>";
} else {
// if all the fields are filled (not empty)
//insert data to database
$sql = "INSERT INTO factory(Fac_Name, Fac_ID) VALUES(:Fac_Name, :Fac_Name)";
$query = $conn->prepare($sql);
$query->bindParam(':Fac_Name', $Fac_ID,);
$query->bindParam(':Fac_ID', $Fac_ID,);
$query->execute();
//display success message
header("Location:factory.php");
}
}
?>
and here is my configPDO.php
<?php
$servername = 'xxx.xx.xx.xxx';
$username = 'xx';
$password = 'xxxxxx';
$dbname = 'xxxx';
try {
$conn = new PDO("sqlsrv:Server=$servername;Database=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $error) {
$error->getMessage();
}
?>
Can I know what the problem? the input at HTML to add the factory is 'Fac_ID'
in the following query
$sql = "INSERT INTO factory(Fac_Name, Fac_ID) VALUES(:Fac_Name, :Fac_Name)";
you are using :Fac_Name twice instead you should use the following
$sql = "INSERT INTO factory(Fac_Name, Fac_ID) VALUES(:Fac_Name, :Fac_ID)";
and if you need to set the same value for the name and id you should ommit the following line
$query->bindParam(':Fac_ID', $Fac_ID,);
since you are trying to bind data to a parameter that doesnt exist in your query
the following statement is sufficent in your case
$query->bindParam(':Fac_Name', $Fac_ID,);

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.

Can't figure out what's wrong with my SQL syntax [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 running the following SQL query in PHP
try {
$sql = "INSERT INTO doc SET type = 1,
candID = :candID,
userID = ".$_SESSION['userid'].",
filename = ".$_FILES['file']['tmp_name'].",
date=date_format(curdate(), '%d/%m/%Y')";
$s = $pdo->prepare($sql);
$s->bindValue(':candID', $_POST['candid']);
$s->execute();
}
catch (PDOException $e) {
$error = 'Error adding doc: ' . $e->getMessage();
include $errorpage;
exit();
}
And I'm getting the following error:
Error adding doc: 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 ':\xampp\tmp\phpD58B.tmp, date=date_format(curdate(),
'%d/%m/%Y')' at line 5
I can't quite figure out why I'm getting this error. Is there something wrong with my syntax that I'm missing?
filename = ".$_FILES['file']['tmp_name'].", should be filename = '".$_FILES['file']['tmp_name']."',
so the code should look like
try {
$sql = "INSERT INTO doc SET type = 1,
candID = :candID,
userID = ".$_SESSION['userid'].",
filename = '".$_FILES['file']['tmp_name']."',
date=date_format(curdate(), '%d/%m/%Y')";
$s = $pdo->prepare($sql);
$s->bindValue(':candID', $_POST['candid']);
$s->execute();
}
catch (PDOException $e) {
$error = 'Error adding doc: ' . $e->getMessage();
include $errorpage;
exit();
}
SET is used for UPDATE statements.
$sql = "INSERT INTO doc (type, candID, userID, finame, date) VALUES (1, :candID, :userID, :filename, :date)";
$s = $pdo->prepare($sql);
$s->execute(array(':candID' => $_POST['candid'], ':userID' => $_SESSION['userid'], ':filename' => $_FILES['file']['tmp_name'], ':date' => date('d/m/Y'));

MySQL Insert using PDO in PHP [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've been trying to get a form to insert records to a MySQL database using a form, but for some reason it errors out on me and I can't figure out why.
Here is the code that processes the request:
if ($_SERVER['REQUEST_METHOD']=='POST'){
// database connection
try {
$dbh = new PDO('mysql:host='.$host.';dbname='.$dbName, $dbUser, $dbPass);
$dbh -> setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$dbh -> exec("SET NAMES 'utf8'");
} catch (Exception $e) {
echo "Error!: " . $e->getMessage() . "<br/>";
die();
}
// new data
$title = $_POST["txtTitle"];
$description = $_POST["txtDesc"];
$content = $_POST["txtContent"];
$sql = "INSERT INTO tblPageContent
SET (PageTitle, Description, PageContent)
VALUES (:title, :desc, :content)";
try {
$update = $dbh->prepare($sql);
$update->bindParam(":title",$title, PDO::PARAM_STR);
$update->bindParam(":desc",$description, PDO::PARAM_STR);
$update->bindParam(":content",$content, PDO::PARAM_STR);
$update->execute();
$id = $update->dbh->lastInsertId();
$update->dbh->commit();
echo $id;
} catch (Exception $e) {
echo "Data could not be updated in the database.";
echo $e;
exit;
}
}
Whenever I try to use it, I end up with this:
exception 'PDOException' with message '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 '(PageTitle, Description, PageContent) VALUES
('Awards', 'This is a test', '' at line 2'
I've tried tweaking the SQL syntax, but I still can't get it to work. Is there something I'm missing here?
Your insert syntax is WRONG.
The correct syntax is:
insert into tblPageContent (pageTitle, Description, PageContent)
values (:title, :desc, :content)
I recommend you have MySQL reference manual at hand
In your SQL, take out the SET before the first (. You use SET in updates, not inserts.

Send message forward along the info [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Send message forward along the info. the info that I select in shell or worse than for the bare lies into the database again what I need .. but the problem is such that it appears with this error:
error 1: Commands out of sync; you can't run this command now
PHP/MYSQLI
if($stmt = $this->mysqli->prepare(' SELECT id, idunik, fra, message, datoTime FROM pm WHERE id = ?' ))
{
$stmt->bind_param('i', $id);
$id = $_GET['id'];
$stmt->execute();
$stmt->bind_result($id, $idunik, $fra, $message, $datoTime);
while($stmt->fetch())
{
if ($stm = $this->mysqli->prepare('INSERT INTO pm (idunik, title, fra, til, message, datoTime) VALUES (?, ?, ?, ?, ?, NOW())')) {
$stm->bind_param('issss', $idunik, $title, $fra, $til, $message);
$idunik = $idunik;
$title = $title;
$fra = $_SESSION["id"];
$til = $fra;
$message = $_POST["tekst"];
header('Location: /besked/' . $_SESSION["id"] . '/');
$stm->execute();
$stm->close();
} else {
echo 'error 1: ' . $this->mysqli->error;
}
}
$stmt->close();
}
else
{
echo 'error 2: ' . $mysqli->error;
}
so the problem is such that when carrying it into the database then comes the error.
Unfortunately your question it not perfectly understandable, so I'm just going to give some general info related to the the error you receive (as I presume this is what you want to resolve):
error 1: Commands out of sync; you can't run this command now
Because Mysqli uses unbuffered queries by default on prepared statements, while Mysqli has previous results to be fetched you cannot call another procedure.
To fix this, and avoid the error you are getting, use mysqli_store_result() to get all rows first, then perform the next query.
mysqli_store_result():
http://php.net/manual/en/mysqli.store-result.php
Transfers the result set from the last query on the database
connection represented by the link parameter to be used with the
mysqli_data_seek() function.
And more info on "commands-out-of-sync":
http://dev.mysql.com/doc/refman/5.1/en/commands-out-of-sync.html

Categories