I am a beginner when we talk about PHP. SO I have no idea where I made a mistake using PHP.
<?php
require "conn.php";
$name = "yolo";
$surname = "yolo";
$nameOfFee= "asd";
$date = '2012-08-06';
$mysql_query = "(INSERT INTO Relation (Person_ID, Fee_ID, Date_of_fee)
SELECT Person.ID,Fee.ID,'$date'
FROM Person,Fee
WHERE Person.Name = '$name' AND Person.Surname = '$surname' AND Fee.Name_of_fee = '$nameOfFee');";
if($conn->query($mysql_query) === TRUE){
echo "Insert completed";
}
else{
echo "Insert not completed";
}
$conn->close();
?>
It always puts that Insert is not complete...
The Problems
There are a few syntax errors in this piece of code you have provided:
// here it starts, what is this "(" for before insert?
// Take note that your query is vulnerable to SQL attacks
$mysql_query = "(INSERT INTO Relation (Person_ID, Fee_ID, Date_of_fee)
SELECT Person.ID,Fee.ID,'$date'
FROM Person,Fee
WHERE Person.Name = '$name' AND Person.Surname = '$surname' AND Fee.Name_of_fee = '$nameOfFee');";
How to fix it
To fix these things I recommend you use the MySQLi OOP, like you are using now, but add prepared statements. I will walk through the new code with you so you can understand the process.
require "conn.php";
$name = "yolo";
$surname = "yolo";
$nameOfFee= "asd";
$date = '2012-08-06';
$sql = "INSERT INTO Relation (Person_ID, Fee_ID, Date_of_fee) VALUES (?, ?, ?)"; // rewrite your query with a preset number of values to prevent SQL Attacks
if($stmt = $conn->prepare( $sql ))
{ // before we run check to make sure the query worked
$stmt->bind_param('sss', $name, $nameOfFee, $date); // bind your variables so to know what goes where
$stmt->execute(); // execute the query
$stmt->close(); // close connection for safety
// message as an array for the user as feedback.
$message = array(
'is_error' => 'success',
'message' => 'Record was entered into database.'
);
}
else
{
$message = array(
'is_error' => 'danger',
'message' => 'Query Error, please revise the information.'
);
}
Related
I am getting "invalid parameter number:parameter undefined" exception when attempting an insert query to mysql database.
I am returning the result to my Android app as json.
if (!empty($_POST))
{
$query = "INSERT INTO attendance (tdate,slot_from,slot_to,coursecode,stud_id,remark) VALUES (:dat,:fromm,:too,:ccode,:stud,:rmk ) ";
$query_params = array(
':dat' => $_POST['datee'],
':from'=>$_POST['fromm'],
':to'=>$_POST['too'],
':ccode'=>$_POST['course'],
':stud'=>$_POST['sname'],
':rmk'=>$_POST['remark'],
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex)
{
//or just use this use this one to product JSON data:
$response["success"] = 0;
$response["message"] = $ex->getMessage();
$response["date"] = $_POST['datee'];
$response["from"] = $_POST['fromm'];
$response["to"] = $_POST['too'];
$response["ccode"] = $_POST['course'];
$response["stud"] = $_POST['sname'];
$response["remark"] = $_POST['remark'];
die(json_encode($response));
}
}
you lack a m in
':from'=>$_POST['fromm'],
should be
':fromm'=>$_POST['fromm'],
you must be careful when using named parameter, I myself am very prone to making such errors
that's why I more easily use the ? placeholder, this way in your exemple:
$query = "INSERT INTO attendance (tdate,slot_from,slot_to,coursecode,stud_id,remark) VALUES (?,?,?,?,?,?) ";
$query_params = array(
$_POST['datee'],
$_POST['fromm'],
$_POST['too'],
$_POST['course'],
$_POST['sname'],
$_POST['remark'],
);
then:
$result = $stmt->execute($query_params);
you must be sure that the params are in good order (same as in query)
In your query, you're misspelling from:
$query = "INSERT INTO attendance (tdate,slot_from,slot_to,coursecode,stud_id,remark) VALUES (:dat,:fromm,:too,:ccode,:stud,:rmk ) ";
Replace it with:
$query = "INSERT INTO attendance (tdate,slot_from,slot_to,coursecode,stud_id,remark) VALUES (:dat,:from,:too,:ccode,:stud,:rmk ) ";
The code is not giving any result can you help me ?
$f_name = $_POST['first_name'];
$l_name = $_POST['last_name'];
$e_mail = $_POST['email'];
$sql = "INSERT INTO
informations(first name, last name,email ,email)
VALUES($f_name,$l_name,$e_mail)";
/*$result = pdo::query($sql);
if(!$result)*/
$result = $sql->fetch(PDO::FETCH_ASSOC);
if(!$result)
{
//something went wrong, display the error
echo 'Something went wrong while registering. Please try again later.';
//echo mysql_error(); //debugging purposes, uncomment when needed
}
else
{
echo 'Successfully registered. You can now sign in and start posting! :-)';
}
You currently aren't using PDO propertly, you're fetching results with an insert query, and you aren't making the most of parameter binding.
Try this:
// make sure $db is initialized as a new PDO object
// use :param placeholders for binding
$sql = "INSERT INTO informations(first name, last name, email) VALUES(:first, :last, :email)";
// prepare query
$query = $db->prepare($sql);
// set up parameter binding replacements
$binding = array(
':first' => $f_name,
':last' => $l_name,
':email' => $e_mail // strange variable name splitting...
);
// execute the query (returns boolean true or false)
$query_results = $query->execute($binding);
// process result message
if($query_results) {
echo 'Success';
} else {
echo 'Something went wrong! Error: ' . $query->errorInfo();
}
For reference:
PDO::execute() manual
PDO introduction tutorial
Another PDO tutorial
mysql_connect('localhost', 'root', '')
or die(mysql_error());
mysql_select_db('shuttle_service_system')
or die(mysql_error());
$insert="INSERT INTO inactive (ID_No, User_Password, First_Name, Last_Name, Email, Contact_Number)
VALUES('". $ID_No ."','". $UserPassword ."','". $FirstName ."','". $LastName ."','". $Email ."','". $ContactNumber ."')";
$result=mysql_query($insert);
$sql="DELETE FROM users WHERE ID_No = '$ID_No'";
$result2=mysql_query($sql);
if($result && $result2){
echo"Successful!";
} else {
echo "  Error";
}
Hi guys I have been stuck in delete function of MySQL, I have tried searching the net but when I ran my code it always goes to the else part which means there is an error, the insert is already okay but the delete is not.
PHP variables are allowed in double quotes. Hence try this,
$sql="DELETE FROM users WHERE ID_No = $ID_No";
Your first query was not properly escaped. Rewrite like
$insert="INSERT INTO inactive (`ID_No`, `User_Password`, `First_Name`, `Last_Name`, `Email`, `Contact_Number`)
VALUES('$ID_No','$UserPassword','$FirstName','$LastName','$Email','$ContactNumber')";
This (mysql_*) extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. Switching to PreparedStatements is even more better to ward off SQL Injection attacks !
First, use PDO.
Make your connection Database like this:
function connectToDB(){
$host='localhost';
try {
$user = 'username';
$pass = 'password';
$bdd = 'databaseName';
$dns = 'mysql:host='.$host.';dbname='.$bdd.'';
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8",
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
return $connexion = new PDO($dns, $user, $pass, $options);
}catch ( Exception $e ) {
echo "Fail to connect: ", $e->getMessage();
die();
}
}
To delete something, here is an example:
function deleteUserWithId($ID_No){
$connexion = connectToDB();
try{
$connexion->exec('DELETE FROM users WHERE ID_No = '.$ID_No);
}catch(Exception $e){
echo "Error: ".$e->getMessage();
}
}
To insert something:
function addInactiveUser($UserPassword,$FirstName ,$LastName ,$Email,$ContactNumber){
$connexion = connectToDB();
$insert = $connexion->prepare('INSERT INTO inactive VALUES(:ID_No,
:User_Password,
:First_Name,
:Last_Name,
:Email,
:Contact_Number
)');
try {
// executing the request
$success = $insert->execute(array(
'ID_No'=>'',
'User_Password'=>$UserPassword,
'First_Name'=>$FirstName ,
'Last_Name'=>$LastName ,
'Email'=>$Email,
'Contact_Number'=>$ContactNumber
));
if($success)
// OK
else
// KO
}
catch (Exception $e){
echo "Error: ".$e->getMessage();
}
}
To make a select:
// If you want to display X user per pages for example
function getAllInactiveUsers($page, $numberInactiveUserPerPage){
$connexion = connectToDB();
$firstInactiveUser = ($page - 1) * $numberInactiveUserPerPage;
$selectAllInactiveUsers = $connexion->prepare('SELECT * FROM inactive ORDER BY ID_No DESC LIMIT '.$firstInactiveUser.','.$numberInactiveUserPerPage);
return $selectAllInactiveUsers ;
}
To get the results of this methods, just do something like this:
$inactiveUsers= getAllInactiveUsers(1,15); // for page 1, display 15 users
$inactiveUsers->execute();
while($row = $inactiveUsers->fetch(PDO::FETCH_OBJ)){
$id = $row->ID_No;
$first_name = $row->First_Name;
// etc...
}
Hope that's help :)
I am not sure if this helps you, but as an alternative you could delete the last entry in the table:
$delQ = mysql_query("SELECT * FROM ph ORDER BY id DESC LIMIT 1" );
while(( $ar = mysql_fetch_array($delQ)) !== false){
mysql_query("DELETE FROM ph WHERE id= $ar[id]");
}
I'm trying to create a SQL query using PHP in which it checks to see if a row has already been submitted/set using the same date and user name. If it hasn't it inserts a new row. If it does find a match, it updates the row instead.
I can insert a new row fine, but when I use a pre-existing date and name, I receive no error in any of my logs, and the query appears to run without any problems. But when checking the database, I notice that there are no UPDATES actually set to the row. When I run the update command manually in SQL, it appears to work fine.
Having no logs/error data to go on, I was hoping to get some advice here. I'm sure there must be something I'm missing here. This is what I'm currently using:
require_once 'db-conn.php';
$name = $_POST['name'];
$email = $_POST['email'];
$date = $_POST['date'];
$var1 = $_POST['var1'];
$var2 = $_POST['var2'];
$var3 = $_POST['var3'];
$var4 = $_POST['var4'];
$conn = db_connect ();
$sqlq = "SELECT * FROM tbl WHERE date = '$date' AND name = '$name'";
$nRows = $conn->query("$sqlq")->fetchColumn();
if ($nRows==0) {
try {
$sqli = "INSERT INTO tbl (name,email,date,var1,var2,var3,var4) VALUES (:name,:email,:date,:var1,:var2,:var3,:var4)";
$sql = $conn->prepare("$sqli");
$sql->execute(array(':name' => $name, ':email' => $email, ':date' => $date, ':var1' => $var1, ':var2' => $var2, ':var3' => $var3 ':var4' => $var4));
} catch(PDOException $e) {
die ('SQL Error');
}
}
else {
try {
$sqli = "UPDATE tbl SET email='$email', notes='$notes', var1='$var1', var2='$var2', var3='$var3' WHERE date='$date' AND name='$name'";
$sql = $conn->prepare("$sqli");
$sql->execute(array($name, $email, $date, $var1, $var2, $var3, $var4));
} catch(PDOException $e) {
die ('SQL Error');
}
}
You don't have the bound variables correct:
$sqli = "UPDATE tbl SET email=:email, notes=:notes, var1=:var1, var2=:var2, var3=:var3 WHERE date=:date AND name=:name";
$sql = $conn->prepare("$sqli");
$sql->execute(array(':name' => $name, ':email' => $email, ':date' => $date, ':var1' => $var1, ':var2' => $var2, ':var3' => $var3, ':notes'=>$notes));
You did it correct in the Insert statement but not in the update.
Not sure where you are getting $notes from though.
Plus not sure if it is intentional or not but you are not updating var4 in the update query.
I've been reworking my website from unprotected MySQL queries to mysqli prepared statements and it all went well until I got this: No data supplied for parameters in prepared statement.
if(empty($err)) {
$pSETQuery = NULL;
if(!empty($_POST['password'])) {
$pSETQuery .= ", password = ?";
}
if($session->isSuperuser()) {
$pSETQuery .= ", usertype = ?";
}
if(!($stmt = $database->prepare("UPDATE user SET username = ?, email = ? $pSETQuery WHERE UserId = ?"))) {
$err[] = "PREPARE FAILED.";
}
$stmt->bind_param("s", $_POST['username']);
$stmt->bind_param("s", $_POST['email']);
if(!empty($_POST['password'])) {
$stmt->bind_param("s", $_POST['password']);
}
if($session->isSuperuser()) {
$stmt->bind_param("s", $_POST['usertype']);
}
$stmt->bind_param("i", $_POST['userid']);
if(!$stmt->execute()){
$err[] = "Execute failed. ERROR: " . $stmt->error;
}
}
The error you are getting is becauses of these lines:
$stmt->bind_param("s", $_POST['username']);
$stmt->bind_param("s", $_POST['email']);
You should only call bind_param() once and you need to provide the same number of variadic variables as you have placeholders in the SQL. This function is not well designed, which is one of the main reasons people prefer PDO.
To solve the problem you need to dynamically prepare 3 things: placeholders, types and variables to bind. Here is how you could dynamically build such query:
if(empty($err)) {
$pSETQuery = '';
$types = 'sss'; // for the three constant placeholders
$data = [$_POST['username'], $_POST['email']];
if(!empty($_POST['password'])) {
$pSETQuery .= ", password = ?";
$types .= 's'; //concat one more
$data[] = $_POST['password'];
}
if($session->isSuperuser()) {
$pSETQuery .= ", usertype = ?";
$types .= 's'; //concat one more
$data[] = $_POST['usertype'];
}
$data[] = $_POST['userid']; // for UserId
$stmt = $database->prepare("UPDATE user SET username = ?, email = ? $pSETQuery WHERE UserId = ?");
$stmt->bind_param($types, ...$data);
$stmt->execute();
}
Do you use Zend Framework ?
It could be a version problem between Php and Zend.
I got the problem with PHP 5.3 + who got the same error on insert or update with Zend framework 1.8.3.
If you are in that case, one of the solutions is to change the connector to the database. Try this, it works for me :
$db = new Zend_Db_Adapter_Pdo_Mysql(array(
'host' => '127.0.0.1',
'username' => 'webuser',
'password' => 'xxxxxxxx',
'dbname' => 'test'
));
"No data supplied for parameters in prepared statement" means statement is ok but at least one of the vars you're providing to bind_param is not there as expected! i would print out $_POST and see what's going on and eventually set $pSETQuery = ''; and not to null!
$_POST['username']
$_POST['email']
$_POST['password']
$_POST['usertype']
$_POST['userid'] // this one is the one I would really watch after, how do you tell the userid if the user is not logged ( i assume that from email, passwrod and might be wrong)
I've just found a way to fix the same problem.
It was a value passed to MySQL, which was NULL. Whereas this column can't be NULL in table definition...