PHP - Check if username has a key yet MORE [duplicate] - php

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 6 years ago.
Im trying to take input from a form, then check table (user) if that name exsits and I need to grab the uid colum.
Input (username / MSG) > Check for username > if so get uid > else add user(This I got) > take uid and use when i INSERT the msg into its table (message)
Table structure:
user: uid (Unique) | name
Heres where in at PHP whise:
<?php
$name = $_GET["name"];
$message = $_GET["message"];
$checkn = "SELECT 1 FROM user WHERE name = $name";
$sql = "INSERT INTO user (uid, name) VALUES ('','$name')";
$msg = "INSERT INTO message (uid, message) VALUES ('$uid','$message')";
$uid = "SELECT uid FROM user WHERE name = $name";
$result = $conn->query($checkn);
if ($conn->query($checkn) === TRUE) {
echo "Checkn TRUE";
}else {
echo "<br> SHEEET" . $checkn . $conn->error;
}
$conn->close();?>
I erased the bulk to start over and get this fixed so once I can get this portion done I have the add if user doesn't exist. Thank you.

I think You are writing the query wrong, when using PHP you should write the query inside ' if it contains variable. " won't parse the variable value.
Replace :
$checkn = "SELECT 1 FROM user WHERE name = $name";
With:
$checkn = 'SELECT 1 FROM user WHERE name = $name';
And it should work. Do the same with other queries too. Use ' instead of "
Hope it helps.

Just from the top of my head
<?php
$name = $_GET["name"];
$message = $_GET["message"];
$checkn = sprintf('SELECT 1 FROM `user` WHERE `name` = \'%s\'', $name);
$sql = sprintf('INSERT INTO `user` (`uid`, `name`) VALUES (\'\',\'%s\')', $name);
$msg = sprintf('INSERT INTO `message` (`uid`, `message`) VALUES (\'%s\',\'%s\')', $uid, $message);
$uid = sprintf('SELECT `uid` FROM `user` WHERE `name` = \'%s\'', $name);
$result = $conn->query($checkn);
if ($conn->query($checkn) == TRUE) {
echo "Checkn TRUE";
} else {
echo "<br> SHEEET" . $checkn . $conn->error;
}
$conn->close();
?>
for some reason i have sometimes had problems when i did not put ` around table names.
I have also separated the variable interpolation so it makes it easier to secure it for sql injection (i did not secure it).
You used triple === this means its strict but mysql would pass 1 back which when using strict is not true.
Hope it helps

Related

Php login system insert trouble

I have an issue with my code. The purpose of the code is just a clear cut login system where you can login and create a user. My issue is with the creating a user. When I fill out the fields it'll say the error message error adding user since the user ID is zero. I asked my teacher and he said there was something wrong with my insert statements but i can't for the life of me figure it out. Can anyone point my in the right direction? Thank you! (the table name is called security)
PHP
$insert_sql ="INSERT INTO security SET ";
$insert_sql .= " username = '".$username ."'";
$insert_sql .= ", first_name = '".$first_name."'";
$insert_sql .= ", last_name = '".$last_name."'";
$insert_sql .= ", email = '".$email."'";
$insert_sql .= ", password = '". $salted_password . "'";
$result = $dbh->query($insert_sql);
$user_id = $dbh->insert_id;
if ($user_id > 0){
session_start();
$_SESSION['user_id'] =$user_id;
echo "Login Created and user logged in<p>";
echo "<a href=main.php>Click here to continue</a><p>";
} else {
$msg = 'Error adding user';
NEW_LOGIN($dbh,$msg);
}
}
}
Your insert statement incorrectly takes the form of a update statement.
$insert_sql ="INSERT INTO security SET ";
$insert_sql .= " username = '".$username ."'";
$insert_sql .= ", first_name = '".$first_name."'";
$insert_sql .= ", last_name = '".$last_name."'";
$insert_sql .= ", email = '".$email."'";
$insert_sql .= ", password = '". $salted_password . "'";
should actually be
$insert_sql ="INSERT INTO security (username_column_in_db, first_name_column_in_db,last_name_column_in_db,email_column_in_db)
values ('".$username ."','".$first_name."','".$last_name."','".$email."','". $salted_password . "')";
username_column_in_db, first_name_column_in_db, last_name_column_in_db and email_column_in_db need to be replaced with column names you have in your database.
Your user id returns as 0 because the record is not actually inserted, not because you tried to make the id as 0.
According to the MySQL Docs, the proper INSERT Statement looks as follows:
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
What you have is:
INSERT INTO security SET ...
Specifically take a look at the part after the columns a,b and c are defined in the first statement. See the difference now? Hope this helps.

Change an Insert statement to an update statement in PHP/MySQL

I'm making an Android app that connects to a database online and lets the user edit the database from the application, I'm new to PHP and MySql but from my research I think I should be using an UPDATE statement, I've written the code below to register new users on the site from a tutorial, but I'd like to change the INSERT statement to an UPDATE statement so that instead of registering a new user, the App updates existing data that I have entered in PHPMYADMIN, could someone show me how to do this? Also, if you require the code for the app mention it in the comments and I'll add it to the question, I don't want to post too much unneccessary code. Thanks in advance.
<?php
require "conn.php";
$patient_name = $_POST["patient_name"];
$check_in_date = $_POST["check_in_date"];
$room_number = $_POST["room_number"];
$bed_number = $_POST["bed_number"];
$notes = $_POST["notes"];
$mysql_qry = "insert into patients(patient_name, check_in_date, room_number, bed_number, notes) values ('$patient_name', '$check_in_date', '$room_number', '$bed_number', '$notes')";
if($conn->query($mysql_qry) === TRUE) {
echo "Insert successful";
}
else{
echo "Error: " . $mysql_qry . "<br>" . $conn->error;
}
$conn->close();
?>
EDIT
The fixed code is below, it now updates records already in the database rather than adding new data.
<?php
require "conn.php";
$patient_name = $_POST["patient_name"];
$check_in_date = $_POST["check_in_date"];
$room_number = $_POST["room_number"];
$bed_number = $_POST["bed_number"];
$notes = $_POST["notes"];
$mysql_qry = "UPDATE patients SET notes='$notes' WHERE patient_name='$patient_name'";
if($conn->query($mysql_qry) === TRUE) {
echo "Insert successful";
}
else{
echo "Error: " . $mysql_qry . "<br>" . $conn->error;
}
$conn->close();
?>
first of all this PHP code is vulnerable to sql injection you should, no need to update your code to use either mysqli prepared statement or PDO prepared statement
secondly the easiest way I know you accomplish your goal would make a unique constraint on some columns and then use a mysql feature ON DUPLICATE UPDATE
for this example I'll assume that the unique fields determining an update instead of an insert are patient_name, check_in_date, room_number, and bed_number (in case john smith was in the same room as john smith in seprate beds) the query to update the table would be like this
ALTER TABLE `patients` ADD UNIQUE `unique_index`(`patient_name`, `check_in_date`, `room_number`, `bed_number`);
so now to address the sql injection bit and the query, I'll update the example to use mysqli statement and will assume patient_name and notes are strings (varchar/nvarchar), room_number and bed_number are integers, and check_in_date is a date
Edit My original answer had a syntax error in the query and also passing variables to the prepared statement below is the updated answer
$mysqliConn = new mysqli("localhost", "my_user", "my_password", "mydatabase");
$stmt = $mysqliConn->prepare("insert into patients
(patient_name, check_in_date, room_number, bed_number, notes)
values (?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE notes=values(notes)");
$patient_name = $_POST["patient_name"];
$check_in_date = $_POST["check_in_date"];
$room_number = $_POST["room_number"];
$bed_number = $_POST["bed_number"];
$notes = $_POST["notes"];
mysqli_stmt_bind_param($stmt, "sdiis",
$patient_name, $check_in_date, $room_number, $bed_number, $notes);
hope this helps
Edit
Regarding the unique key, a unique key means that all fields in the unique key have to be unique when combined so for the example above
if record 1 is
patient_name, check_in_date, room_number, bed_number, notes
'john smith', '3/1/2017' , 413 , 2 , 'patient is sick'
and record two is
'jane doe' , '3/1/2017' , 413 , 2 , 'patient has wound'
these two records will note be duplicates with the above constraint but if you do need to change the constraint you can do the following
DROP the Constraint
ALTER TABLE `patients` DROP INDEX `unique_index`;
Then recreate the constraint like this
ALTER TABLE `patients` ADD UNIQUE `unique_index`(`patient_name`, `check_in_date`, `room_number`);
also if you named your constraint something other than unique_index you can find the key_name by running the following
SHOW INDEX FROM `patients`;
the name will be in the key_name column
additionally you may want to alter the last line of the query to be this in your php if you change the unique constraint so you can change bed number
ON DUPLICATE KEY UPDATE bed_number=values(bed_number), notes=values(notes)
You can also use REPLACE INTO, then you don't have to change the SQL statement. Let MySQL do the work for you.
https://dev.mysql.com/doc/refman/5.7/en/replace.html
<?php
require "conn.php";
$patient_name = $_POST["patient_name"];
$check_in_date = $_POST["check_in_date"];
$room_number = $_POST["room_number"];
$bed_number = $_POST["bed_number"];
$notes = $_POST["notes"];
$mysql_qry = "REPLACE INTO patients(patient_name, check_in_date, room_number, bed_number, notes) VALUES ('$patient_name', '$check_in_date', '$room_number', '$bed_number', '$notes')";
if($conn->query($mysql_qry) === TRUE) {
echo "Insert successful";
}
else{
echo "Error: " . $mysql_qry . "<br>" . $conn->error;
}
$conn->close();
Also, you should really take a look at using PDO with prepared statements and parameters.
https://secure.php.net/manual/en/pdo.prepare.php
Actually I was looking for a small function that converts an INSERT MySQL query to an UPDATE query. So maybe other people were looking for the same and I think this is what the original poster was looking for aswell... I couldnt find any so I made this simple function which works for my needs, ofcourse you will have to make sure your original query is safe from MySQL injection.
It will convert
INSERT INTO aaa (bbb, ccc) VALUES ('111', '222')
to
UPDATE aaa SET ccc='222' WHERE bbb='111'
Use the 2nd variable ($iColumn) to identify the WHERE statement.
function convertInsertToUpdate($sQuery, $iColumn = 1) {
$sNewQuery = "";
$iPos = strpos($sQuery, ' (');
$sTmpTable = substr($sQuery, 0, $iPos);
$iPos = strpos($sTmpTable, 'INSERT INTO ');
$sTmpTable = substr($sTmpTable, $iPos+12);
$iPos = strpos($sQuery, ') VALUES (');
$sTmpValues = substr($sQuery, $iPos+10);
$iPos = strrpos($sTmpValues, ')');
$sTmpValues = substr($sTmpValues, 0, $iPos);
$iPos = strpos($sQuery, '(');
$sTmpColumns = substr($sQuery, $iPos+1);
$iPos = strpos($sTmpColumns, ') VALUES (');
$sTmpColumns = substr($sTmpColumns, 0, $iPos);
$aColumns = explode(', ', $sTmpColumns);
$aValues = explode(', ', $sTmpValues);
if (count($aColumns)>0 && count($aColumns) == count($aValues) && $iColumn < (count($aValues)+1)) {
$sNewQuery = "UPDATE ".$sTmpTable." SET";
$sTmpWhere = "";
$bNotFirst = false;
$iX = 0;
while ($iX<count($aColumns)) {
if ($iColumn == ($iX+1)) {
$sTmpWhere = " WHERE ". $aColumns[$iX]."=".$aValues[$iX];
$iX++;
continue;
}
if ($bNotFirst) {
$sNewQuery .= ",";
}
$sNewQuery .= " ".$aColumns[$iX]."=".$aValues[$iX];
$bNotFirst = true;
$iX++;
}
$sNewQuery .= $sTmpWhere;
}
return $sNewQuery;
}

Inserting values into a table with a PHP-variable name

I'm setting up a simple website where each user gets their own table (bad idea, I know), in which other users can put comments into - like a super budget version of a Facebook-wall.
This is what my query looks like when I create the table:
$userTable = mysqli_query($conn, "CREATE TABLE `".$epost."`(
ID INT(255) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
eMail VARCHAR(50) NOT NULL,
comment VARCHAR(500) NOT NULL,
timestampp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
)");
However, when I try to take the values from a form, and insert them into the specific table they can't seem to find their way in there. Here's my code of that:
<?php
include 'connect.php';
/*if(isset ($_POST['userUser']))*/
$valueEmail = mysqli_real_escape_string($conn, $_POST['userEmail']);
$valueUser = mysqli_real_escape_string($conn, $_POST['userUser']); /*have the user to input the name, so i can connect to the correct DB*/
$valueMessage = mysqli_real_escape_string($conn, $_POST['userMessage']);
$findUserTable = "SELECT * FROM UserInfo WHERE Firstname = '$valueUser'";
$findUserEmail = mysqli_query($conn, $findUserTable);
if(mysqli_num_rows($findUserEmail) > 0) /*finding the name of the persons email*/
{
while ($result = mysqli_fetch_assoc($findUserEmail))
{
$email = $result['Email'];
}
}
/* VALIDATION HERE */
$sql = "INSERT INTO ".$email." (eMail, comment) VALUES ('$valueEmail', '$valueMessage')"; /* wrong query?*/
header("refresh:10 url=userProfil.php");
/*echo '<script>alert("Meddelande skapat!");</script>';*/
echo $sql;
mysqli_close($conn);
?>
I've been trying different 'versions' of the variable, like ".$email.", '.$email.' and ".$epost.". I get the correct name when i echo out my query or just the variable - but it can't seem to find the table?
I'm very aware that my code smells badly, so please spare me on that point.
You just simple write your query forget to execute it.
$sql = "INSERT INTO ".$email." (eMail, comment) VALUES ('$valueEmail', '$valueMessage')"; /* wrong query?*/
Use this
mysqli_query($conn,$sql);//for execute
Better use Bind and prepare statement as
$sql = "INSERT INTO ".$email." (eMail, comment) VALUES (? ,?)"; /* wrong query?*/
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $valueEmail, $valueMessage);
/* Execute the statement */
$stmt->execute();
$row = $stmt->affected_rows;
if ($row > 0) {
echo "data inserted";
} else {
"error";
}
Read http://php.net/manual/en/mysqli-stmt.bind-param.php

Sql appropriate syntax

does the following piece of code face sql injection problems? IF so why and what could be changed to prevent it?
$sql2 = "UPDATE Candidates SET ".$row['Field']."= '$_POST[$tempname]' WHERE ID='".$_GET["id"]."'";
$result2 = mysqli_query($con,$sql2);
if ($con->query($sql2) === TRUE) {
if($_POST['Status']=="Employed"){
$sql3 = "INSERT INTO Employees (AFNumber, CID, Status, Name, DateOfBirth,DateOfEmployment)
VALUES ('".$_POST['AFNumber']."', '".$_POST['ID']."', 'Employed', '".$_POST['FullNameEng']."','".$_POST['DoBasID']."', '".date('d/m/Y')."')";
$result3 = mysqli_query($con,$sql3);
if ($con->query($sql3) === TRUE) {
}else {
echo "Error: " . $sql3 . "<br>" . $con->error;}
echo '<script>swal("Error", "Something went wrong '.$con->error.'", "error");</script>';
}
} else {
echo "Error: " . $sql2 . "<br>" . $con->error;
echo '<script>swal("Error", "Something went wrong '.$con->error.'", "error");</script>';
}
$row['Field'] = "`{$row['Field']}`"; //its better to use ` around field names. there can be 'date', 'begin', 'column' or other reserved keywords http://dev.mysql.com/doc/refman/5.6/en/keywords.html
$_POST[$tempname] = mysqli_real_escape_string($con, $_POST[$tempname]); //have no idea which data type your $row['Field']-column, so lets rely on escaping will be enough http://php.net/manual/en/mysqli.real-escape-string.php
$_GET['id'] = (int)$_GET['id']; //i believe that your `id` is an integer, otherwise you should use mysqli_real_escape_string
$sql2 = "UPDATE Candidates SET ".$row['Field']." = '{$_POST[$tempname]}' WHERE `ID` = '{$_GET['id']}'";
$result2 = mysqli_query($con, $sql2);
if ($con->query($sql2) === TRUE) {
if($_POST['Status']=="Employed") {
$_POST['AFNumber'] = (int)$_POST['AFNumber']; //i believe that your `AFNumber` is an integer, otherwise you should use mysqli_real_escape_string
$_POST['ID'] = (int)$_POST['ID']; //i believe that your `CID` is an integer, otherwise you should use mysqli_real_escape_string
$_POST['FullNameEng'] = mysqli_real_escape_string($con, $_POST['FullNameEng']);
$_POST['DoBasID'] = mysqli_real_escape_string($con, $_POST['DoBasID']); //if DateOfBirth is not a string - u can use (int) instead
$sql3 = "
INSERT INTO Employees
(AFNumber, CID, Status, Name, DateOfBirth, DateOfEmployment)
VALUES
('".$_POST['AFNumber']."', '".$_POST['ID']."', 'Employed', '".$_POST['FullNameEng']."', '".$_POST['DoBasID']."', '".date('d/m/Y')."')
";
//...
The main idea here (also the simplest, minimal) is:
1) if data-type is integer use (int) or intval() on incoming values.
2) if data-type is integer unsingned use abs() on incoming values.
3) othervise (on strings) use mysqli_real_escape_string
Read about Escape Sequences https://dev.mysql.com/doc/refman/5.0/en/string-literals.html
For future read about Prepared Statements https://dev.mysql.com/doc/refman/5.0/en/sql-syntax-prepared-statements.html

Update query works but not insert query

I'm having a problem with inserting info into the database. Strangely the update query works but not the insert query. I don't get any error either when submitting, it goes through correctly and echo account saved but nothing is inserted. What am i missing or doing wrong. please assist
if(isset($_POST['Submitaccount'])){
$allowedusers = $_POST['users'];
$accountid = trim($_POST['accountid']);
if(!$_POST['copyperms']) $_POST['copyperms']='N';
if(!$_POST['allusers']) $_POST['allusers']='N';
if(!$_POST['enabled']) $_POST['enabled']='N';
if(!$_POST['servertime']) $_POST['servertime']='N';
if(!$_POST['delremovals']) $_POST['delremovals']='N';
unset($_POST['Submitaccount']);
unset($_POST['accountid']);
unset($_POST['users']);
$notmust = array("email" , "skip" , "comments" , "firstmod");
foreach($_POST as $key=>$val){
if(!trim($val) && !in_array($key , $notmust)) {
$err = 1;
$empty = "$key";
break;
}
$qpart .= "`$key` = '".mysql_escape_string($val)."' , " ;
}
if($qpart) $qpart = substr($qpart , 0 , -2);
if(!$err){
$chk = mysql_num_rows(mysql_query("SELECT * from accounts WHERE name = '".mysql_escape_string($_POST['name'])."' and id <> '$accountid'"));
if($chk >0){
$err = 2;
}
}
if(!$err){
if(!$accountid){
$q = "INSERT into accounts SET $qpart ";
mysql_query($q) or die("Error inserting the record :".mysql_error()."<br>".$q);
$accountid = mysql_insert_id();
}else{
$q = "UPDATE accounts SET $qpart WHERE id = '$accountid'";
mysql_query($q) or die("Error updating the record :".mysql_error()."<br>".$q);
}
}
This is because the INSERT command has different syntax:
INSERT into accounts SET $qpart "
is not usual, you can write it like this:
INSERT into accounts (column names) VALUES your values"
13.2.5 INSERT Syntax
You have double if(!$err){. Do you want both (!$err) into one? If the first (!$err) is for indicator for the second to insert, function SELECT can not be placed above the function INSERT indirectly.
try this:
if(!$err){
$chk = mysql_num_rows(mysql_query("SELECT * from accounts WHERE name = '".mysql_escape_string($_POST['name'])."' and id <> '$accountid'"));
if($chk >0){
$err = 2;
// if(!$err){ again ...
if(!$accountid){
$q = "INSERT into accounts SET (column1) VALUES ($var1)";
mysql_query($q) or die("Error inserting the record :".mysql_error()."<br>".$q);
$accountid = mysql_insert_id();
}
else{
$q = "UPDATE accounts SET $qpart WHERE id = '$accountid'";
mysql_query($q) or die("Error updating the record :".mysql_error()."<br>".$q);
}
}
}
else{
//other code to handle if ($err)
}
Note: I would prefer using PDO to handle database, it's so simple scripting, besides, it's no longer supported
You have to understand that mysql functions have become deprecated. Either using mysqli or pdo would be the better option, but if you absolutely have to use mysql as a solution i would suggest not posting the form to itself, rather post to another php file as you will have less problems.In my environment it seems to work well as an interim solution while we are rewriting everything to use mysqli.If it a go and let me know.

Categories