$sql="SELECT activity,work_order FROM works";
$result=mysql_query($sql);
while($row=mysql_fetch_assoc($result)){
if($row['work_order']==$work_order && $row['activity']==$activity){
$sql="UPDATE works SET wei_out='$wei_out',len_out='$len_out',end_time='$end_time' WHERE work_order='$work_order' AND activity='$activity'";
break;
}
else{
$sql="INSERT INTO works (jobno,date,start_time,work_order,worker,activity,status,len_in,wei_in,grams) values ('$jobno','$date','$start_time','$work_order','$worker','$activity','$status','$len_in','$wei_in','$grams')";
break;
}
}
the above code for insertion and updation in while loop is not working can anyone help me by solving
You forgot to execute the statement stored in $sql variable and its good to use mysqli for your security issue.
$sql="SELECT activity,work_order FROM works";
$result=mysqli_query($connection, $sql);
while($row=mysqli_fetch_assoc($result)){
if($row['work_order']==$work_order && $row['activity']==$activity){
$sql="UPDATE works SET wei_out='".$wei_out."',len_out='".$len_out."',end_time='".$end_time."' WHERE work_order='".$work_order."' AND activity='".$activity."'";
mysqli_query($connection, $sql);
break;
}
else{
$sql="INSERT INTO works (jobno,date,start_time,work_order,worker,activity,status,len_in,wei_in,grams) values ('".$jobno."','".$date."','".$start_time."','".$work_order."','".$worker."','".$activity."','".$status."','".$len_in."','".$wei_in."','".$grams."')";
mysqli_query($connection, $sql);
break;
}
}
You forgot your mysqli_query(); in your for loop. And please use mysqli_* not mysql_*.
$con = mysqli_connect("localhost", "my_user", "my_password", "my_db");
$sql = "SELECT activity, work_order FROM works";
$result = mysqli_query($con, $sql);
// Don't forget to escape your input!
$len_out = mysqli_real_escape_string($con, $len_out);
$wei_out = mysqli_real_escape_string($con, $wei_out);
$end_time = mysqli_real_escape_string($con, $end_time);
$start_time = mysqli_real_escape_string($con, $start_time);
$work_order = mysqli_real_escape_string($con, $work_order);
$activity = mysqli_real_escape_string($con, $activity);
$jobno = mysqli_real_escape_string($con, $jobno);
$date = mysqli_real_escape_string($con, $date);
$worker = mysqli_real_escape_string($con, $worker);
$status = mysqli_real_escape_string($con, $status);
$len_in = mysqli_real_escape_string($con, $len_in);
$wei_in = mysqli_real_escape_string($con, $wei_in);
$grams = mysqli_real_escape_string($con, $grams);
while ($row = mysqli_fetch_assoc($result)) {
if ($row['work_order'] == $work_order && $row['activity'] == $activity) {
$sql = "UPDATE works SET wei_out='$wei_out', len_out='$len_out', end_time='$end_time' WHERE work_order='$work_order' AND activity='$activity'";
mysqli_query($con, $sql); // Run the query
break;
} else {
$sql = "INSERT INTO works (jobno, date, start_time, work_order, worker, activity, status, len_in, wei_in, grams) VALUES ('$jobno', '$date', '$start_time', '$work_order', '$worker', '$activity', '$status', '$len_in', '$wei_in', '$grams')";
mysqli_query($con, $sql); // Run the query
break;
}
}
Related
The code I have below is suppose to insert some information into a mysql database. For some reason every time I test it I get the error statement that it was not able to execute. Everything looks like it should work to me. Is there something I am missing here?
<?php
include("phpconnect.php");
$name = $_GET["name"];
$date = $_GET["date"];
echo $name;
echo $date;
$sql = "INSERT INTO main (name, visits, visitDate, lastVisit)
VALUES ('$name', '1', '$date', '$date')";
if (mysqli_query($conn, $sql))
{
echo "Records added successfully.";
}
else
{
echo "ERROR: Could not execute $sql. "
.mysqli_error($conn);
}
mysqli_close($conn);
?>
Maybe, you should build your SQL statement slightly different. You can always throw an error message, better for the overview -
$sql = "INSERT INTO main (name, visits, visitDate, lastVisit)
VALUES (?, 1, ?, ?)";
if($stmt = $mysqli->prepare($sql)){
$stmt->bind_param('sss', $name, $date, $date);
if (!$stmt->execute()) {
return false;
// or print error message
} else {
return true;
} else {
return false;
}
Or check this out - MySQL INSERT INTO with PHP $variable !
First Check your datbase connection
Second check your form method GET or POST then apply
Check your table column name
include("phpconnect.php");
if(isset($_POST['submit'])){
$name = $_POST["name"];
$date = $_POST["date"];
$sql = "INSERT INTO main (name, visits, visitDate, lastVisit) VALUES ('$name', '1', '$date', '$date')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
Try something like this. This function accurately inserts into my database and also scrapes for SQL injection.
function addRestaurant() {
if(isset($_POST['submit'])) {
global $connection;
$name = $_POST['name'];
$address = $_POST['address'];
$city = $_POST['city'];
$state = $_POST['state'];
$zipcode = $_POST['zipcode'];
$googlemapslink = $_POST['googlemapslink'];
$restauranttype = $_POST['restauranttype'];
$website = $_POST['website'];
$logo = $_POST['logo'];
$sitelink = $_POST['sitelink'];
if ($googlemapslink == "") {
$googlemapslink = "https://youtu.be/dQw4w9WgXcQ";
}
if ($website == "") {
$website = "https://youtu.be/dQw4w9WgXcQ";
}
if ($logo == "") {
$logo = "https://youtu.be/dQw4w9WgXcQ";
}
$name = mysqli_real_escape_string($connection, $name);
$address = mysqli_real_escape_string($connection, $address);
$city = mysqli_real_escape_string($connection, $city);
$state = mysqli_real_escape_string($connection, $state);
$zipcode = mysqli_real_escape_string($connection, $zipcode);
$googlemapslink = mysqli_real_escape_string($connection, $googlemapslink);
$restauranttype = mysqli_real_escape_string($connection, $restauranttype);
$website = mysqli_real_escape_string($connection, $website);
$logo = mysqli_real_escape_string($connection, $logo);
$sitelink = mysqli_real_escape_string($connection, $sitelink);
$query = "INSERT INTO `restaurants` (Name, Address, City, State, ZipCode, GoogleMapsLink, Website, RestaurantType, RestaurantLogo, SiteLink) ";
$query .= "VALUES (";
$query .= "'$name', ";
$query .= "'$address', ";
$query .= "'$city', ";
$query .= "'$state', ";
$query .= "'$zipcode', ";
$query .= "'$googlemapslink', ";
$query .= "'$website', ";
$query .= "'$restauranttype', ";
$query .= "'$logo', ";
$query .= "'$sitelink'); ";
$filesite = "restaurants/" . $sitelink;
$file = "restaurants/menu.php";
$contents = file_get_contents($file);
file_put_contents($filesite, $contents);
$result = mysqli_query($connection, $query);
if(!$result) {
die("Query failed." . mysqli_error($connection));
} else {
echo "Record updated!";
}
}
}
Can someone find the problem?
It doesn't give any errors, but new rows don't appear in the database and I don't know the problem is.
if (isset( $_REQUEST['signupnbtn'] ) ) {
$age = mysqli_real_escape_string($con,$_REQUEST['ageinput']);
$discord = mysqli_real_escape_string($con,$_REQUEST['discordinput']);
$email = mysqli_real_escape_string($con,$_REQUEST['emailinput']);
$tmp = mysqli_real_escape_string($con,$_REQUEST['tmpinput']);
$steam = mysqli_real_escape_string($con,$_REQUEST['steaminput']);
$datum = date("d-m-Y");
$errorcode = 0;
$q = "INSERT INTO `admissions` (age, discord, email, tmp, steam, datum)
VALUES ('$age', '$discord', '$email', '$tmp', '$steam', '$datum')";
$query2 = "SELECT email FROM `admissions` WHERE email='$email'";
$sql = mysqli_query($con,$query2);
$countrows = mysqli_num_rows($sql);
if($countrows >= 1){
$errorcode = 1;
}else {
$result = mysqli_query($con,$q);
}
if ($result) {
$errorcode = 4;
}
}
$q = "INSERT INTO admissions (age, discord, email, tmp, steam, datum) VALUES ('$age', '$discord', '$email', '$tmp', '$steam', '$datum')";
Problem solved, the date should be in "Y-m-d" format instead of "d-m-Y" as below:
if (isset( $_REQUEST['signupnbtn'] ) ) {
$age = mysqli_real_escape_string($con,$_REQUEST['ageinput']);
$discord = mysqli_real_escape_string($con,$_REQUEST['discordinput']);
$email = mysqli_real_escape_string($con,$_REQUEST['emailinput']);
$tmp = mysqli_real_escape_string($con,$_REQUEST['tmpinput']);
$steam = mysqli_real_escape_string($con,$_REQUEST['steaminput']);
$datum = date("Y-m-d");
$errorcode = 0;
$q = "INSERT INTO `admissions` (age, discord, email, tmp, steam, datum)
VALUES ('$age', '$discord', '$email', '$tmp', '$steam', '$datum')";
$query2 = "SELECT email FROM `admissions` WHERE email='$email'";
$sql = mysqli_query($con,$query2);
$countrows = mysqli_num_rows($sql);
if($countrows >= 1){
$errorcode = 1;
}else {
$result = mysqli_query($con,$q);
}
if ($result) {
$errorcode = 4;
}
}
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 did a lot of googling and tried many methods but checking for username existence in Mysqli database is not working. Everything is correct but still the user is getting registered even if there is a username in Database. Please help...My php version is 7 and phpmyadmin is 5.6. My code :-
<?php
session_start();
if (isset($_SESSION['id'])) {
header('Location: user.php');
die();
}
else {
if($_POST['submit']){
$username = strip_tags($_POST['username']);
$email = strip_tags($_POST['email']);
$password = strip_tags($_POST['password']);
$passhash = hash('sha512', $password);
$passhash2 = hash('sha512', $passhash);
$strlen = strlen("$password");
if ($strlen < 10) { {
$lesspass = "Use password of atleast 10 letters";
}
}
else {
$date = date("Y-m-d");
require ('setup.php');
$conn = new mysqli($localhost, $hostuser, $hostpass, $hostdb) or die("conn died");
$query1 = "SELECT * FROM member WHERE username = '$username'";
$result1 = mysqli_query($conn, $query1);
if (mysqli_num_rows($query1) > 0) {
die ("Username in use");
}
else {
$query2 = "SELECT from member WHERE email = $email";
$result2 = mysqli_query($conn, $query2);
if (($result2) > 0) {
$ee = "Email already exists";
}
else {
$query = "INSERT INTO member(username, password, registered, email, activated, status) VALUES('$username', '$passhash2', '$date', '$email', '1', '0')";
$result = mysqli_query($conn, $query);
if($result) {
header('Location: login.php');
}
else {
echo "There was a problem while connecting";
}
}
}
}
}
}
?>
I think the error is that you use mysqli_num_rows on the query string. Do it on the result:
if (mysqli_num_rows($result1) > 0) {
Also, you should take care about SQL injections (escape or use prepared statements), but that's another story. Not sure if strip_tags is sufficient.
I am trying to see the best approach for this scenario - i want to send an email alert whenever a user updates a specific column. The column name is rep. If the rep column isnt updated, do not send an email.
Here's my attempt:
<?php
include_once("connection.php");
if(isset($_POST['update'])) {
$id = mysqli_real_escape_string($mysqli, $_POST['record_update']);
$record_update = mysqli_real_escape_string($mysqli, $_POST['record_update']);
$comment = mysqli_real_escape_string($mysqli, $_POST['comment']);
$status = mysqli_real_escape_string($mysqli, $_POST['status']);
$rt = mysqli_real_escape_string($mysqli, $_POST['rt']);
$reason = mysqli_real_escape_string($mysqli, $_POST['reason']);
$username = mysqli_real_escape_string($mysqli, $_POST['username']);
$rep = mysqli_real_escape_string($mysqli, $_POST['rep']);
if(empty($record_update) ) {
if(empty($record_update)) {
echo "<script type='text/javascript'>alert('Date/Time field is blank.');window.location.href='dashboard.php';</script>";
}
} else {
$result = mysqli_query($mysqli, "UPDATE employee SET record_update='$record_update', comment='$comment', status='$status', rt='$rt', reason='$reason', username='$username', rep='$rep' WHERE id='$id'");
if($rep->(success() == true)) {
//do email
}
}
?>
so would it look like this?
<?php
include_once("connection.php");
if(isset($_POST['update'])) {
$id = mysqli_real_escape_string($mysqli, $_POST['record_update']);
$record_update = mysqli_real_escape_string($mysqli, $_POST['record_update']);
$comment = mysqli_real_escape_string($mysqli, $_POST['comment']);
$status = mysqli_real_escape_string($mysqli, $_POST['status']);
$rt = mysqli_real_escape_string($mysqli, $_POST['rt']);
$reason = mysqli_real_escape_string($mysqli, $_POST['reason']);
$username = mysqli_real_escape_string($mysqli, $_POST['username']);
$rep = mysqli_real_escape_string($mysqli, $_POST['rep']);
if(empty($record_update) ) {
if(empty($record_update)) {
echo "<script type='text/javascript'>alert('Date/Time field is blank.');window.location.href='dashboard.php';</script>";
}
} else {
$query = mysqli_query($mysqli, "SELECT rep FROM employee WHERE id='$id'");
$row = $query->fetch_assoc()[0];
if($row['rep'] != $_POST['rep']) {
//do nothing
} else {
//do email
}
$result = mysqli_query($mysqli, "UPDATE employee SET record_update='$record_update', comment='$comment', status='$status', rt='$rt', reason='$reason', username='$username', rep='$rep' WHERE id='$id'");
}
?>
Select the current value, and compare it to the inserted value, if it's different it needs to be updated?
$query = mysqli_query($mysqli, "SELECT rep FROM employee WHERE id='$id'");
$row = $query->fetch_assoc()[0];
if($row['rep'] != $_POST['rep'])
$record_update = true;
This might not be the best answer but I like to suggest that you capture the date and time of the first insert and then the update record them in a table columns and the compare the time or both when an update happens to the same data row.
$query = mysqli_query($mysqli, "SELECT time, date FROM employee WHERE id='$id'");
$row = $query->fetch_assoc()[0];
if($row['time'] > $_POST['time'] || $row['date'] > $_POST['date'])
$record_update = true;