I have the following code which is part of a function to add a user to a database in PHP. It adds a user to a database.
if($user != '' && $pass != ''){
$new_name_q = "INSERT IGNORE INTO $db_name (`User`, `Password` ,`Name`, `Medals`, `TextSize`)
VALUES ('$user','$pass','$nameComplete', '000000', '18')";
$new_name_rs = mysqli_query($connection1,$new_name_q);
if(!$new_name_rs)
{
die("No name added: " . mysql_error());
}
}
The query works fine and I don't get any duplicates.
But I would like to echo a warning to the user in case the query is ignored.
Here's the code you need:
if($user != '' && $pass != ''){
$new_name_q = "INSERT IGNORE INTO $db_name (`User`, `Password` ,`Name`, `Medals`, `TextSize`)
VALUES ('$user','$pass','$nameComplete', '000000', '18')";
$new_name_rs = mysqli_query($connection1,$new_name_q);
$affected = mysqli_affected_rows($connection1);
if(!$affected) {
die("No name added");
}
}
See http://www.php.net/manual/en/mysqli.affected-rows.php
[I'm assuming here that you've done things like ensuring the variables are properly escaped already]
Related
I have the below code that should add user input into the db, I can't understand why its not adding to db, the email field in the table is a foreign key that references to another table, and I'm using session to store email in the $email and save it to db when user saves data, also I'm accepting date and time from user input which is exactly as per the db format but it still doesn't save, I have tried entering static data as well, not working either. Am I missing something ?
$server = "localhost";
$user = "root";
$pwd = "";
$sql_db = "cabcustomers";
$email = $_SESSION['sesName'];
$conn = #mysqli_connect($server,$user,$pwd,$sql_db);
if (isset ($_POST["name"]) && isset ($_POST["contact"]) && isset ($_POST["unitno"]) && isset ($_POST["streetno"]) && isset ($_POST["streetname"]) && isset ($_POST["suburb"]) && isset ($_POST["destsuburb"]) && isset ($_POST["pickdt"]) && isset ($_POST["picktime"]))
{
$name = $_POST["name"];
$contact = $_POST["contact"];
$unitno = $_POST["unitno"];
$streetno = $_POST["streetno"];
$streetname = $_POST["streetname"];
$suburb = $_POST["suburb"];
$destsuburb = $_POST["destsuburb"];
$pickdt = $_POST["pickdt"];
$picktime = $_POST["picktime"];
if(empty($name) || empty($contact) || empty($unitno) || empty($streetno) || empty($streetname) || empty($suburb) || empty($destsuburb) || empty($pickdt) || empty($picktime))
{
echo "<p>ONE OR MORE OF FIELDS HAVE MISSING INFORMATION, KINDLY CHECK AND TRY AGAIN!</p>";
}
elseif (!is_numeric($contact))
{
echo "<p>CONTACT NUMBER MUST BE NUMERIC!</p>";
}
else
{
$idlen = 7;
$bookingid = uniqid (rand(), true);
$bookingid = "BK" . substr($bookingid, 0, $idlen);
$status = "unassigned";
$pickdt = $pickdt . " " . $picktime;
$query = "insert into bookings (bookingid, pname, contact, unitno, streetno, streetname, suburb, destsuburb, pickupdt, bookingdt, status, email) values ('$bookingid', '$name', '$contact', '$unitno', '$streetno', '$streetname', '$suburb', '$destsuburb','$pickdt', 'NOW()','$status', '$email');";
echo $email;
$result = mysqli_query($conn, $query);
echo $result;
echo "<p>INFORMATION SAVED</p>";
}
mysqli_close($conn);
}
Based on the comments after your initial question, I don't think the connection is the problem, the problem is most likely happening during the INSERT query. Have you tried running the query from phpMyAdmin to troubleshoot the syntax of the query outside of PHP?
This script is selecting data based on optional fields in a HTML form. Although they are optional fields, at least 1 must be entered with the idea being that the more fields entered, the more likely you are to get a single result. For test I have two records with the same first and last name but different ID's and mobile numbers. At the moment when entering a name, 2 fields are given... Correct but when entering a mobile or ID, two results are still displayed.
Ive tried reading into passing missing variables in an SQL query but haven't got very far. Anything blindingly obviously wrong?
Thanks
<?php
include "checkmysqlconnect.php";
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$mobile = $_POST['mobile'];
$attendid = $_POST['attendid'];
$search = $_POST['search'];
if ($search == "Search") {
if ($firstname == '' AND $lastname == '' AND $attendid == '' AND $mobile == '') {
header("Location: searchattendform.php?result=1");
$error = true;
}
if($error != true) {
$sql = "SELECT * FROM `attend` WHERE `firstname` = '".$firstname."' AND `lastname` = '".$lastname."' AND `attendid` = '".$attendid."' AND `mobile` = '".$mobile."'";
$query = mysql_query($sql);
$count = mysql_num_rows($query);
if ($count > 1) {
while($value = mysql_fetch_assoc($query)) {
echo "More than one attendee with this name. Entering more details will help narrow down results.";
echo "<tr><td>".$value['attendid']."</td><td>".$value['wristband']."</td><td>".$value['firstname']."</td><td>".$value['lastname']."</td><td>".$value['telephone']."</td><td>".$value['mobile']."</td><td>".$value['address1']."</td><td>".$value['address2']."</td><td>".$value['town']."</td><td>".$value['postcode']."</td><td>".$value['email']."</td><td>".$value['medical']."</td></tr>";
} } else {
if ($count == 0) {
header("Location: searchattendform.php?result=2");
} else {
if ($count == 1) {
($value = mysql_fetch_assoc($query));
echo "<tr><td>".$value['attendid']."</td><td>".$value['wristband']."</td><td>".$value['firstname']."</td><td>".$value['lastname']."</td><td>".$value['telephone']."</td><td>".$value['mobile']."</td><td>".$value['address1']."</td><td>".$value['address2']."</td><td>".$value['town']."</td><td>".$value['postcode']."</td><td>".$value['email']."</td><td>".$value['medical']."</td></tr>";
} else {
echo "The was an issue searching attendees. Please contact SOFia Admin.";
} }
}
}
}
?>
One issue you have is that your query always checks all the variables:
$sql = "SELECT * FROM `attend` WHERE `firstname` = '".$firstname."' AND `lastname` = '".$lastname."' AND `attendid` = '".$attendid."' AND `mobile` = '".$mobile."'";
You probably want to break it up, and build it dynamically, something like this:
$sql = "SELECT * FROM `attend` WHERE ";
$whereArray = [];
if ($lastName){
$whereArray[] = "`lastname` = '".$lastname."'";
}
if ($firstname){
$whereArray[] = "`firstname` = '".$firstname."'";
}
//etc...
$sql .= join(" AND ", $whereArrray);
You will need to modify this to use parametrization, but this should see you in the right direction:
include "checkmysqlconnect.php";
((isset($_POST['firstname']) && $_POST['firstname'] != '') ? $firstname = '%'.$_POST['firstname'].'%' : null); //prevents unneeded variables
...
if (!(isset($firstname) or isset($lastname) or isset($attendid) or isset($mobile))) { //checks that at least one variable has been provided
...
$sql = "SELECT * FROM `attend` WHERE 1=1"; //returns all; necessary for building the query since you have an unknown number of parameters
(isset($firstname) ? $sql .= " AND `firstname` like '".$firstname."': null); //adds to the query only if the variable exists
...
?>
I highly recommend using some kind of database wrapper class. This will help generate the SQL for you. There are many other reasons why this is a good idea.
There are plenty of MySQL wrappers and most frameworks have one. You could try for example, CodeIgniter, which is very simple framework to install and work with. Then, to create the query you would do something like:
<?php
if(isset($_POST['firstname']) && !empty($_POST['firstname'])) {
$this->db->where('firstname', $_POST['firstname']);
}
if(isset($_POST['lastname']) && !empty($_POST['lastname'])) {
$this->db->where('lastname', $_POST['lastname']);
}
...
$results = $this->db->>get('attend');
foreach($results->result() as $row)
{
echo $row->firstname;
}
?>
Try to place var_dump($sql); die(); after the $sql statement and test what that returns.
end web developer, i was given a CMS done from another team and i have to link with my front-end. I have made some modifications, but due to my lack of php knowledge i have some issue here.
My users are able to fill up a form, where 1 text field is asking for their photo link. I want to check for if the value entered is not equal to what i want, then i will query insert a default avatar photo link to mysql to process.
code that i tried on php
// check if the variable $photo is empty, if it is, insert the default image link
if($photo = ""){
$photo="images/avatarDefault.png";
}
doesn't seem to work
<?php
if($_SERVER["REQUEST_METHOD"] === "POST")
{
//Used to establish connection with the database
include 'dbAuthen.php';
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
//Used to Validate User input
$valid = true;
//Getting Data from the POST
$username = sanitizeInput($_POST['username']);
$displayname = sanitizeInput($_POST['displayname']);
$password = sanitizeInput($_POST['password']);
//hash the password using Bcrypt - this is to prevent
//incompatibility from using PASSWORD_DEFAULT when the default PHP hashing algorithm is changed from bcrypt
$hashed_password = password_hash($password, PASSWORD_BCRYPT);
//Determining Type of the User
//if B - User is student
//if A - User is adin
if($_POST['type'] == 'true')
$type = 'B';
else
$type = 'A';
$email = sanitizeInput($_POST['email']);
$tutorGroup = sanitizeInput($_POST['tutorGroup']);
$courseID = sanitizeInput($_POST['courseID']);
$description = sanitizeInput($_POST['desc']);
$courseYear = date("Y");
$website = sanitizeInput($_POST['website']);
$skillSets = sanitizeInput($_POST['skillSets']);
$specialisation = sanitizeInput($_POST['specialisation']);
$photo = sanitizeInput($_POST['photo']);
// this is what i tried, checking if the value entered is empty, but doesn't work
if($photo = ""){
$photo="images/avatarDefault.png";
}
$resume = sanitizeInput($_POST['resume']);
//Validation for Username
$sql = "SELECT * FROM Users WHERE UserID= '$username'";
if (mysqli_num_rows(mysqli_query($con,$sql)) > 0){
echo 'User already exists! Please Change the Username!<br>';
$valid = false;
}
if($valid){
//Incomplete SQL Query
$sql = "INSERT INTO Users
VALUES ('$username','$displayname','$hashed_password','$type','$email', '$tutorGroup', ";
//Conditionally Concatenate Values
if(empty($courseID))
{
$sql = $sql . "NULL";
}
else
{
$sql = $sql . " '$courseID' ";
}
//Completed SQL Query
$sql = $sql . ", '$description', '$skillSets', '$specialisation', '$website', '$courseYear', '$photo', '$resume', DEFAULT)";
//retval from the SQL Query
if (!mysqli_query($con,$sql))
{
echo '*Error*: '. mysqli_error($con);
}
else
{
echo "*Success*: User Added!";
}
}
//if student create folder for them
if ($type == 'B')
{
//Store current reporting error
$oldErrorReporting = error_reporting();
//Remove E_WARNING from current error reporting level to prevent users from seeing code
error_reporting($oldErrorReporting ^ E_WARNING);
//Set current reporting error();
error_reporting($oldErrorReporting);
}
mysqli_close($con);
}
}
function sanitizeInput($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
i've tried finding a way on mysql to insert default values but it seem impossible, so i have no choice but to query insert through php.
I have the logic but i'm not sure how to implement on the php with my lack of knowledge, i was thinking of checking either
1) if the photo link does not have the word .png/.jpg, $photo != ".png"
2) if the photo link length is too low $.photo.length < 10
can someone help me look into the code and tell me what i'm doing wrong? Thanks!
A very simple way with default values could be:
$photo = isset($photo) ? $photo : 'images/avatarDefault.png' ;
How it works is that it first it asks if the photo is set, if it is, use all ready inserted value, otherwise insert your default value,
Another (very alike) method to use:
$photo = !empty($photo) ? $photo : 'images/avatarDefault.png' ;
UPDATE
To check if it contains a certain "extension" would be a simple rewrite
$photo = preg_match('#\b(.jpg|.png)\b#', $photo ) ? $photo : "images/avatarDefault.png" ;
This way it checks wether the text / image link in $photo contains the .png file type, if it doesn't it inserts your default image
First thing that I notice is to use double =
if($photo == ""){
//...
}
I have two steps sign up form. From the first step I'm picking up email and username and from second step I want to pick up first name and lastname and add it into DB.
But the problem is that variables which I've got from the first POST form, $bridge_username to be exact, is not available in the IF statement below (the first one from the bottom). The thing is that they are visible anywhere else, but not inside this particular IF statement. I've tried everything, including sessions. I can clearly see that variable is still there (using vardump or just echoing it out), everywhere but not where I need it...
I'll be happy to hear your advises.
$bridge_email = $_POST['email'];
$bridge_username = $_POST['username'];
$bridge_pass = $_POST['password'];
$bridge_pass_conf = $_POST['passconf'];
$bridge_terms = $_POST['terms'];
$bridge_pass_counted = strlen($bridge_pass);
$bridge_username_counted = strlen($bridge_username);
if (isset ($_POST['email']) AND isset ($_POST['password']) AND isset ($_POST['passconf']) AND isset ($_POST['username'])) {
if ($bridge_email != '' AND $bridge_pass != '' AND $bridge_pass_conf != '' AND $bridge_username != '' AND $bridge_terms != '') {
if ($bridge_pass == $bridge_pass_conf) {
if ($bridge_pass_counted >= 33 OR $bridge_pass_counted <= 5) {
} else {
if ($bridge_username_counted >= 65 OR $bridge_username_counted <= 3) {
} else {
if (is_numeric(substr($bridge_username, 0, 1))) {
} else {
//CHECK IF USERNAME OR EMAIL ALREADY EXIST
$checkreguser = $mysqli->query("SELECT username FROM `engine_users` WHERE username = '$bridge_username' OR email = '$bridge_email' LIMIT 0, 1 ");
$checkreguser = $checkreguser->fetch_assoc();
if ($checkreguser == '') {
//CREATING A NEW USER
$mysqli->query("INSERT INTO `users` (`id`, `username`, `password`, `email`, `fname`, `lname`, `company`, `address`, `city`, `state`, `zip`, `country`, `currency`, `phone`, `vat`, `userlevel`, `created`, `notes`, `lastlogin`, `lastip`, `active`) VALUES\n"
. "(NULL, '$bridge_username', '1411678a0b9e25ee2f7c8b2f7ac92b6a74b3f9c5', '$bridge_email', '', '', NULL, '', '', '', '', '', '', '', NULL, 5, '2011-05-01 18:10:14', '', '2013-04-19 22:25:11', '127.0.0.1', 'y')");
}}}}}}}
$bridge_fname = $_POST['1_1_3'];
$bridge_lname = $_POST['1_1_4'];
if (isset ($_POST['1_1_3']) AND isset ($_POST['1_1_4'])) {
$mysqli->query("UPDATE `users` SET `fname` = '$bridge_fname',`lname` = '$bridge_lname' WHERE `users`.`username` = '$bridge_username'");
}
I fixed your code a bit to make you a good example,
main issue was how you build your query string
..." username = '$bridge_username' "
this will result in a string like you see it
(it is good debug to print the queries, before executing them)
you have to change it to:
." username = '".$bridge_username."' "
and the variable will be replaced with its value.
Also added checks for the post values, so you don't get warnings if they are not set.
$bridge_email = (isset($_POST['email']) ? $_POST['email'] : null);
$bridge_username = (isset($_POST['username']) ? $_POST['username'] : null);
$bridge_pass = (isset($_POST['password']) ? $_POST['password'] : null);
$bridge_pass_conf = (isset($_POST['passconf']) ? $_POST['passconf'] : null);
$bridge_terms = (isset($_POST['terms']) ? $_POST['terms'] : null);
//$bridge_pass_counted = strlen($bridge_pass);
//$bridge_username_counted = strlen($bridge_username);
//return early and stay back from chained IFs
if (!$bridge_email || !$bridge_username || !$bridge_pass || !$bridge_pass_conf) {
return;
}
if ($bridge_pass != $bridge_pass_conf) {
return;
}
if ($bridge_pass AND strlen($bridge_pass) > 5 AND strlen($bridge_pass) < 33) {
return;
}
if ($bridge_username AND strlen($bridge_username) > 5 AND strlen($bridge_username) < 33) {
return;
}
if (is_numeric(substr($bridge_username, 0, 1))) {
return;
}
$result = $mysqli->query("SELECT username FROM `engine_users` WHERE username = '" . $bridge_username . "' OR email = '" . $bridge_email . "' LIMIT 0, 1 ");
$checkreguser = $result->fetch_assoc(); // returns associative array of strings or NULL if there are no more rows
//if ($checkreguser == '') {
if ($checkreguser === null) {
//CREATING A NEW USER
$mysqli->query("INSERT INTO `users` (`id`, `username`, `password`, `email`, `fname`, `lname`, `company`, `address`, `city`, `state`, `zip`, `country`, `currency`, `phone`, `vat`, `userlevel`, `created`, `notes`, `lastlogin`, `lastip`, `active`) VALUES\n"
. "(NULL, '" . $bridge_username . "', '1411678a0b9e25ee2f7c8b2f7ac92b6a74b3f9c5', '" . $bridge_email . "', '', '', NULL, '', '', '', '', '', '', '', NULL, 5, '2011-05-01 18:10:14', '', '2013-04-19 22:25:11', '127.0.0.1', 'y')");
}
$bridge_fname = (isset($_POST['1_1_3']) ? $_POST['1_1_3'] : null);
$bridge_lname = (isset($_POST['1_1_4']) ? $_POST['1_1_4'] : null);
if ($bridge_fname AND $bridge_lname ) {
$mysqli->query("UPDATE `users` SET `fname` = '" . $bridge_fname . "',`lname` = '" . $bridge_lname . "' WHERE `users`.`username` = '" . $bridge_username . "'");
}
Please examine the IF structure, returning early makes the code more readable.
http://php.net/manual/en/function.isset.php
I would try and break your code down to a simple few lines and test the if statement. Better to identify where it is breaking. Maybe add some echo statements during different steps or comment and step through the code. Example below.
$bridge_email = $_POST['email'];
$bridge_pass = $_POST['password'];
if (isset($_POST['email']) AND isset($_POST['password']){
// EXECUTE AN ALERT
echo"email and pass are set";
}else {
echo"not passing";
}
Use
if(isset($_POST['bridge_username']))
To see if it exists.
You can also use the ternary operator:
$email = isset($_POST['bridge_username']) ? $_POST['bridge_username'] = false;
And ye.. "$bridge_username to be exact, is not available in the IF statement below."
Show us the exact error if you want a more detailed answer :)
Are you checking to see if the session has been started. I see that you keep mentioning that the data was passed to session. May want to set this up to make sure that it is getting handled.
Try checking that the session variable was created and if not redirect back to the registration/login page.
As an example... if the session is not registered it will move to a different script or location.
session_start();
if(!session_is_registered(myusername)){
header("location:main_login.php");
you could further test the session by echoing contents on an isset on session to keep testing. Again, I would break your code down into the most basic form to learn what is going on. Might also need to see the prior page code to see what is happening.
found another example online that might help you out. http://www.phpeasystep.com/phptu/6.html
The following code is part of my ajax notification system and for some reason, it is working only 50%. When I call the code, it runs and then echo's either success or remove but it doesn't seem to change the database values. Any reason? I have tried putting my column names in quotes but that echo's an error. Please help, thanks!
<?php
require_once('.conf.php');
$notid = mysql_real_escape_string($_GET['notification_id']);
$username = mysql_real_escape_string($_SESSION['uname']);
$action = mysql_real_escape_string($_GET['action']);
if ($action == 'add') {
$insert = mysql_query("UPDATE updates SET object_fav = '1' WHERE username = '$username' AND id = '$notid'") or die('Could not connect: ' . mysql_error());
echo 'success';
} elseif($action == 'sub') {
$remove = mysql_query("UPDATE updates SET object_fav = '0' WHERE username = '$username' AND id = '$notid'") or die('Could not connect: ' . mysql_error());
echo 'remove';
} else {
echo 'error';
}
?>
I know it is not the javascript, I have checked the network tab and it is sending the correct values.
If this is the start of the script, you have not called session_start(), and therefore $_SESSION['uname'] will contain an empty value. The query succeeds because it is syntactically correct, but doesn't match any rows and therefore performs no update.
session_start();
require_once('.conf.php');
$notid = mysql_real_escape_string($_GET['notification_id']);
$username = mysql_real_escape_string($_SESSION['uname']);
$action = mysql_real_escape_string($_GET['action']);
Echo $insert and $remove and find which values are missing.