if(isset($_GET['id'])){
$nome = $_GET['nome'];
$cognome = $_GET['cognome'];
$id = $_GET['id'];
$sql = "UPDATE utenti SET nome = :nome, cognome = :cognome WHERE id = :id";
$req = $dbh->prepare($sql);
$req->execute(
array(
":nome" => $nome,
":cognome" => $cognome,
":id" => $id,
)
);
} else {
$nome = $_GET['nome'];
$cognome = $_GET['cognome'];
$sql = "INSERT INTO utenti (nome, cognome) VALUES (:nome, :cognome)";
$req = $dbh->prepare($sql);
$req->execute(
array(
":nome" => $nome,
":cognome" => $cognome,
)
);
}
Hello everyone. I have this code that inserts or updates a form's data within a database. I would like to include an "if" check that you are checking that the user does not already exist in the database. How can I do? Thank you
Try this:
$nome = $_GET['nome'];
//Searching the nome in the database
$req = $dbh->prepare("SELECT COUNT(*) AS anzahl FROM user WHERE Benutzername = :nome");
//Counts the rows with the given nom
$req->bindParam(':nome', $nome, PDO::PARAM_STR);
$req->execute();
$result = $req->fetch();
if ($result[0] > 0) {
//already exists - A row was found
echo "Already exists";
}
else {
//not existing - There was no row with that username
"Your Insertquery, use $req2 here"
}
Edit 2: This should work now ^^
Related
Im trying to add data to diferent tables in MySQL, but at the moment of run my code, it shows me a error is it "Fatal error: Uncaught Error: Call to a member function query()", is the firs time that y use the query function so I don't know whats going wrong.
<?php
session_start();
$_SESSION['ID_user'];
$id = $_SESSION['ID_user'];
$name = $_POST['name'];
$company = $_POST['company'];
$password = $_POST['password'];
$password = password_hash($password, PASSWORD_DEFAULT);
if($name == "" && $password == "" && $company == "" ){
return false;
}
else {
require './conectar.php';
$resultset = $conn->prepare("SELECT * FROM user WHERE ID_user = '$id' LIMIT 1");
$resultset->execute();
$resultkey = $resultset->fetch();
if($resultkey !== false) {
$update = "UPDATE user SET Name_user='$name', password='$password' WHERE ID_user = '$id' LIMIT 1";
$up = $conn->prepare($update);
$up->bindParam(':name', $_POST['name'], FILTER_SANITIZE_SPECIAL_CHARS);
$up->execute();
$result = $up->fetch();
$_SESSION['Name_user'] = $result['name'];
$lastid = $conn->query("SELECT last_insert_id()")->fetch();
$insert = "INSERT INTO rel_company_user (ID_user) VALUES ('$id')";
$in = $conn->prepare($insert);
$in->execute();
$insert = "INSERT INTO company (Name_company) VALUES ('$company')";
$in = $conn->prepare($insert);
$in->execute();
$update = "UPDATE rel_company_user SET ID_company='$lastid' WHERE ID_user = '$id' LIMIT 1";
$up = $conn->prepare($update);
$up->execute();
}
}
header('Location: http://seth.com/dashboard?ftime=1');
/* Pedir el id y actualizarlo */
?>
You should use parameters in all your queries. And you can't use bindParam() if you didn't put a placeholder in the query.
FILTER_SANITIZE_SPECIAL_CHARS is not a valid argument to bindParam(). The third argument is an optional data type.
You never set $thelast anywhere, that should be $conn.
If $id is already assigned, you can't use LAST_INSERT_ID() to get ID_user. Just insert that value into the user table.
You don't need to perform a query to get the last insert ID. Just use LAST_INSERT_ID() in the VALUES list of the next INSERT query.
You can't fetch the results of an UPDATE query.
You can't get the last insert ID if you haven't done an insert. The UPDATE user query should be INSERT INTO user.
In several places you assigned the SQL to $insert, but then did $conn->prepare($update).
<?php
session_start();
$id = $_SESSION['ID_user'];
$name = $_POST['name'];
$company = $_POST['company'];
$password = $_POST['password'];
$password = password_hash($password, PASSWORD_DEFAULT);
if($name == "" && $password == "" && $company == "" ){
return false;
}
else {
require './conectar.php';
$resultset = $conn->prepare("SELECT * FROM user WHERE ID_user = :id LIMIT 1");
$resultset->bindParam(':id', $id);
$resultset->execute();
$resultkey = $resultset->fetch();
if($resultkey !== false) {
$update = "INSERT INTO user (ID_user, Name_user, password) VALUES (:id, :name, :password)";
$up = $conn->prepare($update);
$up->bindParam(':id', $id);
$up->bindParam(':name', $name);
$up->bindParam(':password', $password);
$up->execute();
$result = $up->fetch();
$_SESSION['Name_user'] = $name;
$insert = "INSERT INTO rel_company_user (ID_user) VALUES (:id)";
$in = $conn->prepare($insert);
$in->bindParam(':id', $id);
$in->execute();
$insert = "INSERT INTO company (Name_company) VALUES (:company)";
$in = $conn->prepare($insert);
$in->bindParam(':company', $company);
$in->execute();
$update = "INSERT INTO rel_company_user (ID_company, ID_user) VALUES (LAST_INSERT_ID(), :id)";
$up = $conn->prepare($update);
$up->bindParam(':id', $id);
$up->execute();
}
}
header('Location: http://seth.com/dashboard?ftime=1');
/* Pedir el id y actualizarlo */
?>
Is there a better way to do these queries?
I call these functions from an other php to get data back to my Android Application in JSON.
But I feel that this code is "dirty".
This code works. But can there be issues if there are many user requests? I want to keep all the stuff fast an slim for following stuff. Now there are about 100 people running this app. Everything is ok now. But how it will be if there are more?
<?php require_once("db_connection.php");?>
<?php
define('TIMEZONE', 'Europe/Paris');
date_default_timezone_set(TIMEZONE);
function storeUser($email, $password, $uuid, $name){
global $connection;
$date = date("Y-m-d H:i:s");
$query = "SELECT * FROM treuepass_users_all WHERE email ='{$email}'";
$res = mysqli_query($connection, $query);
$num = mysqli_num_rows($res);
if ($num == 0)
{
$query = "SELECT * FROM treuepass_users_all WHERE uuid ='{$uuid}'";
$res = mysqli_query($connection, $query);
$num = mysqli_num_rows($res);
if ($num > 0)
{
$query2 = "UPDATE treuepass_users_all SET email = '{$email}', password = '{$password}', name = '{$name}' WHERE uuid ='{$uuid}'";
$res2 = mysqli_query($connection, $query2);
return $res2;
mysqli_close($connection);
}
else //////Wenn sich HANDY das erste mal anmeldet
$query = "INSERT INTO treuepass_users_all (uuid, dateofregister, email, password, name) VALUES ('{$uuid}', '{$date}', '{$email}', '{$password}', '{$name}')";
$res = mysqli_query($connection, $query);
$query2 = "UPDATE treuepass_users_all SET lastlogin = '{$date}', logincounter = logincounter +1 WHERE uuid ='{$uuid}'";
$res2 = mysqli_query($connection, $query2);
return $res2;
mysqli_close($connection);
}else{
return false;
}
}
function getUserByUsernameAndPassword($email, $password, $uuid){
$date = date("Y-m-d H:i:s");
global $connection;
$query1 = "UPDATE treuepass_users_all SET uuid = '{$uuid}', lastlogin = '{$date}', logincounter = logincounter +1 WHERE email = '{$email}' AND password = '{$password}'";
$user1 = mysqli_query($connection, $query1);
$query2 = "SELECT * FROM treuepass_users_all WHERE email = '{$email}' AND password = '{$password}'";
$user2 = mysqli_query($connection, $query2);
if($user2){
while ($res = mysqli_fetch_assoc($user2)){
return $res;
}
}
else{
return false;
}
mysqli_close($connection);
}
function getUserByUUID($uuid){
global $connection;
//////Wenn UUID bereits Vorhanden
$date = date("Y-m-d H:i:s");
$query2 = "UPDATE treuepass_users_all SET lastlogin = '{$date}', logincounter = logincounter +1 WHERE uuid ='{$uuid}'";
$res2 = mysqli_query($connection, $query2);
$query = "SELECT * FROM treuepass_users_all WHERE uuid ='{$uuid}'";
$res = mysqli_query($connection, $query);
$num = mysqli_num_rows($res);
if ($num > 0)
{
while ($dsatz = mysqli_fetch_assoc($res))
return $dsatz;
mysqli_close($connection);
}
else //////Wenn sich HANDY das erste mal anmeldet
$query = "INSERT INTO treuepass_users_all (uuid, dateofregister, lastlogin, logincounter) VALUES ('{$uuid}', '{$date}', '{$date}', '1')";
$res = mysqli_query($connection, $query);
$query3 = "SELECT * FROM treuepass_users_all WHERE uuid ='{$uuid}'";
$res3 = mysqli_query($connection, $query3);
if($res3){
while ($res = mysqli_fetch_assoc($res3)){
return $res;
}
}
else{
return false;
}
mysqli_close($connection);
}
function getUpdateUserDataLocation($locationid, $id, $stampcard1counter, $stampcard1stampsnow, $stampcard1redeemed, $stampcard2counter, $stampcard2stampsnow, $stampcard2redeemed, $stampcard3counter, $stampcard3stampsnow, $stampcard3redeemed, $vouchercounter, $vouchernow, $voucherredeemed){
global $connection;
$date = date("Y-m-d H:i:s");
$locationtable5 = "treuepass_history_$locationid";
$query5 = "INSERT INTO $locationtable5 (uuid, date, time, stampcard1counter, stampcard1redeemed, stampcard2counter, stampcard2redeemed, stampcard3counter, stampcard3redeemed, voucherredeemed)
VALUES ('$id', '$date', '$date', '$stampcard1counter','$stampcard1redeemed', '$stampcard2counter','$stampcard2redeemed', '$stampcard3counter','$stampcard3redeemed', '$voucherredeemed')";
mysqli_query($connection, $query5);
$locationtable = "treuepass_users_$locationid";
$query3 = "UPDATE $locationtable
SET
stampcard1counter = stampcard1counter+'{$stampcard1counter}', stampcard1stampsnow = '{$stampcard1stampsnow}', stampcard1redeemed = stampcard1redeemed+'{$stampcard1redeemed}',
stampcard2counter = stampcard2counter+'{$stampcard2counter}', stampcard2stampsnow = '{$stampcard2stampsnow}', stampcard2redeemed = stampcard2redeemed+'{$stampcard2redeemed}',
stampcard3counter = stampcard3counter+'{$stampcard3counter}', stampcard3stampsnow = '{$stampcard3stampsnow}', stampcard3redeemed = stampcard3redeemed+'{$stampcard3redeemed}',
vouchercounter = vouchercounter+'{$vouchercounter}', vouchernow = '{$vouchernow}', voucherredeemed = voucherredeemed+'{$voucherredeemed}'
WHERE uuid ='{$id}'";
$res3 = mysqli_query($connection, $query3);
$query = "SELECT * FROM $locationtable WHERE uuid ='{$id}'";
$res = mysqli_query($connection, $query);
$num = mysqli_num_rows($res);
if ($num > 0)
{
while ($dsatz = mysqli_fetch_assoc($res))
return $dsatz;
mysqli_close($connection);
} ////////////////////////////////////////////
else // Wenn sich HANDY das erste mal anmeldet //
$query = "INSERT INTO $locationtable (uuid, stampcard1counter, stampcard1stampsnow, stampcard1redeemed, stampcard2counter, stampcard2stampsnow, stampcard2redeemed, stampcard3counter, stampcard3stampsnow, stampcard3redeemed, vouchercounter, vouchernow, voucherredeemed)
VALUES ('$id', '$stampcard1counter','$stampcard1stampsnow','$stampcard1redeemed', '$stampcard2counter','$stampcard2stampsnow','$stampcard2redeemed', '$stampcard3counter','$stampcard3stampsnow','$stampcard3redeemed',
'$vouchercounter','$vouchernow','$voucherredeemed')";
mysqli_query($connection, $query);
mysqli_close($connection);
}
function getUsersLocationStampcard($userid, $locationid){
global $connection;
$locationtable = "treuepass_users_$locationid";
$query = "SELECT * FROM $locationtable WHERE uuid ='{$userid}'";
$res = mysqli_query($connection, $query);
if($res){
while ($response = mysqli_fetch_assoc($res)){
return $response;
}
}
else{
return false;
}
mysqli_close($connection);
}
?>
Thanks for all the Comments!
I spend the whole day for rewrite my code xD
But now i get all the stuff you told me.
- I did the thing with the connection inside the php
- I only have 1 php for all the stuff now
- Password Hashing with 'password_hash()'
- Prepared Statemants for MySQLi
Here some Snippet:
//////////////////////////////////////////////////STORE USER
if (isset($_POST['uuid']) && isset($_POST['email']) && isset($_POST['password']) && isset($_POST['name'])) {
$sql = "SELECT * FROM treuepass_users_all WHERE email = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s", $_POST['email']);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows == 1)
{
$response["error"] = TRUE;
$response["error_msg"] = "E-Mail Adresse bereits registriert!";
echo json_encode($response);
exit;
}else{
$sql = "INSERT INTO treuepass_users_all (uuid, dateofregister, email, password, name, lastlogin, logincounter) VALUES (?, ?, ?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE email=?, password=?, name=?, lastlogin=?, logincounter=logincounter +1";
$stmt = $mysqli->prepare($sql);
$one = "1";
$hash = password_hash($_POST['password'], PASSWORD_DEFAULT);
$stmt->bind_param("sssssssssss", $_POST['uuid'], $date, $_POST['email'], $hash, $_POST['name'], $date, $one, $_POST['email'], $hash, $_POST['name'], $date);
$stmt->execute();
$sql = "SELECT * FROM treuepass_users_all WHERE uuid = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s", $_POST['uuid']);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc())
{
$response["error"] = FALSE;
$response["user"]["id"] = $row['id'];
$response["user"]["uuid"] = $row['uuid'];
$response["user"]["locked"] = $row['locked'];
$response["user"]["dateofregister"] = $row['dateofregister'];
$response["user"]["email"] = $row['email'];
$response["user"]["username"] = $row['username'];
$response["user"]["name"] = $row['name'];
$response["user"]["surname"] = $row['surname'];
$response["user"]["dayofbirth"] = $row['dayofbirth'];
$response["user"]["monthofbirth"] = $row['monthofbirth'];
$response["user"]["yearofbirth"] = $row['yearofbirth'];
$response["user"]["gender"] = $row['gender'];
$response["user"]["lastlogin"] = $row['lastlogin'];
$response["user"]["logincounter"] = $row['logincounter'];
echo json_encode($response);
}
}
}
I hope i did it well? :)
I want to find out how to output data from database based on a single key,for example my database column are :
kodeDosen(PrimaryKey),namaDosen,email,telepon,password
and my login screen the user can only input kodeDosen and password,and i want to show the other data exept password,this is my register php:
<?php
include 'connectdb.php';
$data = json_decode(file_get_contents('php://input'), true);
$kodeDosen =$data["kodeDosen"];
$namaDosen = $data["namaDosen"];
$email = $data["email"];
$telepon = $data["telepon"];
$password= $data["password"];
$message = array("message"=>"Success");
$failure = array("message"=>"Failure,kodeDosen already used");
$sql = "INSERT INTO tbl_dosen (kodeDosen, namaDosen, email, telepon, password) VALUES ('$kodeDosen', '$namaDosen', '$email', '$telepon','$password')";
if (mysqli_query($conn, $sql)) {
echo json_encode($message);
} else {
echo json_encode($failure) ;
}
?>
and this is my login php:
<?php
include 'connectdb.php';
$data = json_decode(file_get_contents('php://input'), true);
$kodeDosen =$data["kodeDosen"];
$password = $data["password"];
$message = array("message"=>"Data found");
$failure = array("mesage"=>"Data not found");
if ($stmt = mysqli_prepare($conn, "SELECT kodeDosen, namaDosen, email, telepon FROM tbl_dosen WHERE kodeDosen =? and password = ?")) {
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "ss", $kodeDosen,$password);
/* execute query */
mysqli_stmt_execute($stmt);
/* store result */
mysqli_stmt_store_result($stmt);
if(mysqli_stmt_num_rows($stmt) > 0) {
echo json_encode($row);
}else {
echo json_encode($failure);
}
}
?>
It's not a good idea to insert a variable directly into an SQL query because of SQL injection.
I would suggest to use prepared statements on both of the queries. To pull the result from the db with prepared statements it's something like:
OOP style:
$stmt = $db->prepare("SELECT kodeDosen, namaDosen, email, telepon FROM tbl_dosen WHERE kodeDosen = ? and password = ?");
$stmt->bind_param('ss', $kodeDosen, $password);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
//result is in row
var_dump($row);
}
Procedural style:
$stmt = mysqli_prepare($conn, "SELECT kodeDosen, namaDosen, email, telepon FROM tbl_dosen WHERE kodeDosen = ? and password = ?");
mysqli_stmt_bind_param($stmt, 'ss', $kodeDosen, $password);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = $result->fetch_assoc()) {
//result is in row
var_dump($row);
}
You can change in sql SELECT statement in login.php
$sql = "SELECT kodeDosen, namaDosen, email, telepon FROM tbl_dosen WHERE kodeDosen ='$kodeDosen' and password = '$password'";
in SELECT * means return all columns.
I think you want echo json_encode($row); rather than echo json_encode($message);
Try:
<?php
include 'connectdb.php';
$data = json_decode(file_get_contents('php://input'), true);
$kodeDosen =$data["kodeDosen"];
$password = $data["password"];
$message = array("message"=>"Data found");
$failure = array("mesage"=>"Data not found");
if ($stmt = mysqli_prepare($conn, "SELECT kodeDosen, namaDosen, email, telepon FROM tbl_dosen WHERE kodeDosen =? and password = ?")) {
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "ss", $kodeDosen,$password);
/* execute query */
mysqli_stmt_execute($stmt);
/* store result */
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_assoc( $result );
if(mysqli_num_rows($result) > 0) {
echo json_encode($row);
}else {
echo json_encode($failure);
}
}
?>
When I login it's suppose to insert, but instead does nothing.. On my register php it inserts data to accounts, but when i insert data into online it won't work..
PS- I'm new to PDO so I don't know what i'm doing wrong
<?php
session_start();
if(isset($_SESSION['users']) != ""){
echo '<script type="text/javascript">','index();','</script>';
}
include('../php/dbConnect.php');
$username = $_POST['username'];
$password = $_POST['password'];
$query = 'SELECT * FROM `accounts` WHERE username = ?';
$queryprepare = $conn->prepare($query);
$queryprepare->bindParam(1, $username, PDO::PARAM_STR);
$queryprepare->execute();
$row = $queryprepare->fetch();
if($row['password'] == md5($password))
{
$_SESSION['online'] = true;
$_SESSION['users'] = $username;
$_SESSION['userid'] = $row['id'];
$_SESSION['name'] = $row['name'];
$_SESSION['age'] = $row['age'];
$_SESSION['image'] = $row['image'];
$check_row = 'SELECT * FROM `online` WHERE username = ?';
$check_row_fetch = $conn->prepare($check_row);
$check_row_fetch->bindParam(1, $username, PDO::PARAM_STR);
$check_row_fetch->execute();
$number_of_rows = $check_row_fetch->rowCount();
if($number_of_rows != 0) {
echo '<script type="text/javascript">','redirect();','</script>';
}
else{
$online_insert = 'INSERT INTO online (username, name, age, image) VALUES (?, ?, ?, ?)';
$online_insert_fetch = $conn->prepare($online_insert);
$online_insert_fetch->bindParam(1, $SESSION['users'], PDO::PARAM_STR);
$online_insert_fetch->bindParam(2, $SESSION['name'], PDO::PARAM_STR);
$online_insert_fetch->bindParam(3, $SESSION['age'], PDO::PARAM_STR);
$online_insert_fetch->bindParam(4, $SESSION['image'], PDO::PARAM_STR);
$online_insert_fetch->execute();
echo '<script type="text/javascript">','redirect();','</script>';
}
}
else{
echo("Wrong Credentials");
}
?>
I am trying to write a script for a student registration page, where a student enters his/her student id and if it exists then retrieve his/her email and generate a token and insert the token into the database and then send a registration url link with token and id to the student's email..how would i get that since i am a beginner in php and mysql.
where am i going wrong here?
<?php
error_reporting(1);
session_start();
include 'includes/connect.php';
include 'includes/tokengenerator.php';
if ($_POST["Submit"] == "Submit") {
$stu_id = $_POST['stu_id'];
$sql = "SELECT email FROM people WHERE stu_id = :stu_id";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':stu_id', $stu_id);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if (!empty($result)) {
$email = $result['email'];
//echo $email;
//exit();
for ($i = 1; $i <= 2; $i++) {
$token = generateToken();
//echo $token;
$email = $result['email'];
$sql = "INSERT INTO students (token) VALUES ($token) WHERE email = :email";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
':token' => $token,
));
$result1 = $stmt->fetch(PDO::FETCH_ASSOC);
}
} else {
echo 'Please Contact principal for student ID';
}
}
?>
You are binding the wrong value in the query: :token vs :email.
You should actually have 2 placeholders and bind both values.
$sql = "INSERT INTO students (token) VALUES (:token) WHERE email = :email";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
':token' => $token,
':email' => $email
));
And as noted correctly by #Saty, you cannot have a WHERE clause on an INSERT statement:
$sql = "INSERT INTO students (token, email) VALUES (:token, :email)";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
':token' => $token,
':email' => $email
));
Or you might need an UPDATE statement instead of an INSERT:
$sql = "UPDATE students SET token = :token WHERE email = :email";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
':token' => $token,
':email' => $email
));