I'm trying to validate a unique entry when editing/updating a record.
I am validating by searching the database, if the entry is not found then proceed else print an error message. If an entry (I am using this same process when adding new records)
My validation code is:
if (!empty($_POST['ip_add'])) {
if (filter_var($_POST['ip_add'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false) {
$errors[] = $_POST['ip_add'] . ' is not a valid IPv4';
} else {
$ip = $_POST['ip_add'];
//check if ip is unique
$qip = 'select INET_NTOA(ip_add) AS ip_add from equipment where ip_add = INET_ATON(:ip)';
$database->query($qip);
$database->bind(':ip', $ip);
$rs = $database->resultset();
//execute our query
$database->execute();
if ($rs != null) {
$errors[] = $_POST['ip_add'] . ' is not unique';
} else {
$ip_add = $_POST['ip_add'];
}
}
} else {
$errors[] = "Please enter a valid IP address";
}
if there are no errors update database:
$query = "
UPDATE equipment
SET site_code = :site_code,
site_id = :site_id,
system_name = :system_name,
ip_add = INET_ATON(:ip_add),
mcast = INET_ATON(:mcast),
sys_loc = :sys_loc,
systype = :systype,
itamname = :itamname,
dimetis = :dimetis,
DNS = :DNS
WHERE id = :id
";
//prepare query for excecution
$database->query($query);
//bind the parameters
$database->bind(':site_code', $site_code);
$database->bind(':site_id', $site_id);
$database->bind(':system_name', $system_name);
$database->bind(':ip_add', $ip_add);
$database->bind(':mcast', $multicast);
$database->bind(':sys_loc', $sys_loc);
$database->bind(':systype', $systype);
$database->bind(':itamname', $itamname);
$database->bind(':dimetis', $_POST['dimetis']);
$database->bind(':DNS', $_POST['DNS']);
$database->bind(':id', $_POST['id']);
// Execute the query
$database->execute();
echo "Record was updated.";
}
}
I was thinking I could search on all records execpt current record that I am currently editing.
How would I do this?
Is there a better way for checking if IP addrss is unique when editing a record?
I got this to work be excluding current record from search:
$qip = '
SELECT
INET_NTOA(ip_add) AS ip_add
FROM equipment
WHERE
ip_add = INET_ATON(:ip)
AND id != :id
';
$database->query($qip);
$database->bind(':ip', $ip);
$database->bind(':id', $id);
Related
I have used someone else's code that uses the ipaddress way. However, I would like to use a code that checks for the current userid and the id number.
$ipaddress = md5($_SERVER['REMOTE_ADDR']); // here I am taking IP as UniqueID but you can have user_id from Database or SESSION
/* Database connection settings */
$con = mysqli_connect('localhost','root','','database');
if (mysqli_connect_errno()) {
echo "<p>Connection failed:".mysqli_connect_error()."</p>\n";
} /* end of the connection */
if (isset($_POST['rate']) && !empty($_POST['rate'])) {
$rate = mysqli_real_escape_string($con, $_POST['rate']);
// check if user has already rated
$sql = "SELECT `id` FROM `tbl_rating` WHERE `user_id`='" . $ipaddress . "'";
$result = mysqli_query( $con, $sql);
$row = mysqli_fetch_assoc();//$result->fetch_assoc();
if (mysqli_num_rows($result) > 0) {
//$result->num_rows > 0) {
echo $row['id'];
} else {
$sql = "INSERT INTO `tbl_rating` ( `rate`, `user_id`) VALUES ('" . $rate . "', '" . $ipaddress . "'); ";
if (mysqli_query($con, $sql)) {
echo "0";
}
}
}
//$conn->close();
In your database table, set the user_id column as UNIQUE KEY. That way, if a user tries to cast a second vote, then the database will deny the INSERT query and you can just display a message when affected rows = 0.
Alternatively, (and better from a UX perspective) you can preemptively do a SELECT query for the logged in user before loading the page content:
$allow_rating = "false"; // default value
if (!$conn = new mysqli("localhost", "root","","database")) {
echo "Database Connection Error: " , $conn->connect_error; // never show to public
} elseif (!$stmt = $conn->prepare("SELECT rate FROM tbl_rating WHERE user_id=? LIMIT 1")) {
echo "Prepare Syntax Error: " , $conn->error; // never show to public
} else {
if (!$stmt->bind_param("s", $ipaddress) || !$stmt->execute() || !$stmt->store_result()) {
echo "Statement Error: " , $stmt->error; // never show to public
} elseif (!$stmt->num_rows) {
$allow_rating = "true"; // only when everything works and user hasn't voted yet
}
$stmt->close();
}
echo "Rating Permission: $allow_rating";
And if they already have a row in the table, then don't even give them the chance to submit again.
I have a partner table and I need to send reply via SMS. So my table contains firm name, city, mobile and pincode. If someone sends me a pin code via SMS, I want to get back to the customer with the 2 or 3 records (Multiple). With this code I am able to send only one record.
$sql = "SELECT * FROM reg_dealer WHERE pincode = '$myvalue'";
$q = mysql_query($sql);
$rows= mysql_num_rows($q);
$res= mysql_fetch_array($q);
$firm_name=$res['firm_name'];
$city=$res['city'];
$mobiledealer=$res['mobile'];
$pincode=$res['pincode'];
if($res['pincode']=='')
{
$mobile = $_GET['mobile'];
$reply_message = "Greeting. We will get back to you soon on the nearest Partner details.";
$reply_message1 = urlencode($reply_message);
mysql_query("INSERT INTO history(sender,message,datetime,datenew,code,status,reply_message,url)VALUES('$mobile','$message','$datetime','$datenew','$number','Dealer Does Not Exist','$reply_message','$s')");//insert data in to table
}
// part 2
else
{
$mobile = $_GET['mobile'];
$reply_message = "Greetings. Please find the nearest Partner - ".$firm_name.", ".$city.", +".$mobiledealer.".";
$reply_message1 = urlencode($reply_message);
mysql_query("INSERT INTO history(sender,message,datetime,datenew,code,status,reply_message,url)VALUES('$mobile','$message','$datetime','$datenew','$number','Dealer Details Sent','$reply_message','$s')");//insert data in to table
}
Use while loop.
$sql = "SELECT * FROM reg_dealer WHERE pincode = '$myvalue'";
$q = mysql_query($sql);
$rows= mysql_num_rows($q);
while($res= mysql_fetch_array($q))
{
$firm_name=$res['firm_name'];
$city=$res['city'];
$mobiledealer=$res['mobile'];
$pincode=$res['pincode'];
if($res['pincode']=='')
{
$mobile = $_GET['mobile'];
$reply_message = "Greeting. We will get back to you soon on the nearest Partner details.";
$reply_message1 = urlencode($reply_message);
mysql_query("INSERT INTO history(sender,message,datetime,datenew,code,status,reply_message,url)VALUES('$mobile','$message','$datetime','$datenew','$number','Dealer Does Not Exist','$reply_message','$s')");//insert data in to table
}
// part 2
else
{
$mobile = $_GET['mobile'];
$reply_message = "Greetings. Please find the nearest Partner - ".$firm_name.", ".$city.", +".$mobiledealer.".";
$reply_message1 = urlencode($reply_message);
mysql_query("INSERT INTO history(sender,message,datetime,datenew,code,status,reply_message,url)VALUES('$mobile','$message','$datetime','$datenew','$number','Dealer Details Sent','$reply_message','$s')");//insert data in to table
}
}
Update with new requirement:
$mobile = $_GET['mobile'];
$sql = "SELECT * FROM reg_dealer WHERE pincode = '$myvalue'";
$q = mysql_query($sql);
$rows= mysql_num_rows($q);
while($res= mysql_fetch_array($q))
{
$firm_name=$res['firm_name'];
$city=$res['city'];
$mobiledealer=$res['mobile'];
$pincode=$res['pincode'];
if($res['pincode']=='')
{
$reply_message .= "Greeting. We will get back to you soon on the nearest Partner details.";
mysql_query("INSERT INTO history(sender,message,datetime,datenew,code,status,reply_message,url)VALUES('$mobile','$message','$datetime','$datenew','$number','Dealer Does Not Exist','$reply_message','$s')");//insert data in to table
}
// part 2
else
{
$reply_message .= "Greetings. Please find the nearest Partner - ".$firm_name.", ".$city.", +".$mobiledealer.".";
mysql_query("INSERT INTO history(sender,message,datetime,datenew,code,status,reply_message,url)VALUES('$mobile','$message','$datetime','$datenew','$number','Dealer Details Sent','$reply_message','$s')");//insert data in to table
}
}
if (isset($reply_message) && $reply_message != '')
{
$reply_message1 = urlencode($reply_message);
if($res['pincode']=='')
{
mysql_query("INSERT INTO history(sender,message,datetime,datenew,code,status,reply_message,url)VALUES('$mobile','$message','$datetime','$datenew','$number','Dealer Does Not Exist','$reply_message1','$s')");//insert data in to table
}
// part 2
else
{
mysql_query("INSERT INTO history(sender,message,datetime,datenew,code,status,reply_message,url)VALUES('$mobile','$message','$datetime','$datenew','$number','Dealer Details Sent','$reply_message1','$s')");//insert data in to table
}
}
You are fetching only single record because you are not using any type of loop for getting multiple records.
Use while loop:
while($res= mysql_fetch_array($q))
{
//put your below inside the loop
}
Hy there, I guess I've tried everything I could. Somehow my form doesn't work.
I get an ID through the URL - Which I try to use to update the MySQL table
I use the same Form also to input a new Record and there is no problem. But to update it doesn't work at all.
if (true !=$fehler)
{
if ($clientid == 'new')
{
$qy = 'INSERT INTO tbl_clientdb (
clientid,
c_update,
c_Uupdate,
c_Gender,
c_IDNumber,
c_Name,
c_Firstname,
c_Middlename,
c_idCity,
c_idCountry,
c_idLanguage,
c_Phone,
c_Cellphone,
c_Email,
c_Note,
c_idCompany
)
VALUES (
NULL,
NOW(),
"'.$c_Uupdate.'",
"'.$c_Gender.'",
"'.$c_IDNumber.'",
"'.$c_Name.'",
"'.$c_Firstname.'",
"'.$c_Middlename.'",
"'.$c_idCity.'",
"'.$c_idCountry.'",
"'.$c_idLanguage.'",
"'.$c_Phone.'",
"'.$c_Cellphone.'",
"'.$c_Email.'",
"'.$c_Note.'",
"'.$c_idCompany.'"
)';
} else {
$qy = 'UPDATE
tbl_clientdb
SET
c_update = NOW(),
c_Uupdate = "'.$c_Uupdate.'",
c_Gender = "'.$c_Gender.'",
c_IDNumber = "'.$c_IDNumber.'",
c_Name = "'.$c_Name.'",
c_Firstname = "'.$c_Firstname.'",
c_Middlename = "'.$c_Middlename.'",
c_idCity = "'.$c_idCity.'",
c_idCountry = "'.$c_idCountry.'",
c_idLanguage = "'.$c_idLanguage.'",
c_Phone = "'.$c_Phone.'",
c_Cellphone = "'.$c_Cellphone.'",
c_Email = "'.$c_Email.'",
c_Note = "'.$c_Note.'",
c_idCompany = "'.$c_idCompany.'"
WHERE
clientid = '.$clientid.'
LIMIT 1';
}
if ($res = mysql_query($qy))
{
echo 'Your data has been saved successfully';
}
else
{
echo mysql_error();
$meld = 'Please try again';
}
}`
anybody an idee what could be the trouble?
thx a lot for any inputs.
$qy = 'SELECT
clientid,
c_update,
c_Uupdate,
c_Gender,
c_IDNumber,
c_Name,
c_Firstname,
c_Middlename,
c_idCity,
c_idCountry,
c_idLanguage,
c_Phone,
c_Cellphone,
c_Email,
c_Note,
c_idCompany
FROM tablename WHERE id='$id' LIMIT 1";
$query = mysqli_query($yourConnection, $qy) or die (mysqli_error());
While ($row = mysqli_fetch_array($query)) {
/* Create a variable to hold all the data */
$c_update = $row['c_update'];
/* Do same for the rest */
}
Mysqli_free_result($query);
?>
Hope this helps
I couldn't find any error. I tried the query on phpmyadmin and it works well but when I do in php page, it couldn't update into DB. The following code below:
$registerID = ($_POST['registerID']);
$firstName = ucwords(htmlspecialchars($_POST['firstName']));
$lastName = ucwords(htmlspecialchars($_POST['lastName']));
$emailAddress = htmlspecialchars($_POST['emailAddress']);
$mainAddress = ucwords(htmlspecialchars($_POST['fullAddress']));
$updateCity = ucwords($_POST['userCity']);
$updateCountry = $_POST['userCountry'];
$postalCode = strtoupper(htmlspecialchars($_POST['userZip']));
$profilePic = $_POST['pic'];
$updateProf = " UPDATE register_user
SET firstName='$firstName',
lastName='$lastName',
emailAddress='$emailAddress',
mainAddress='$mainAddress',
registerCity='$updateCity',
registerCountry='$updateCountry',
postalCode='$postalCode'
WHERE registerID = '$registerID'";
if (mysqli_query($mysqli, $updateProf)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($mysqli);
}
In the end, there are no errors after I updated on the webpage, it just show Record updated successfully. But it didn't update into DB. Any ideas?
UPDATED CODING
$checkProfile = "SELECT * FROM register_user where emailAddress = '$emailAddress'";
$editProfile = mysqli_query($mysqli,$checkProfile);
if ($editProfile) {
if (mysqli_num_rows($editProfile) > 0) {
header("Location: event?error=That name of email has already been taken");
} else {
$updateQuery = "UPDATE register_user
SET firstName = '$firstName',
lastName = '$lastName',
emailAddress = '$emailAddress',
mainAddress = '$mainAddress',
registerCity = '$updateCity',
registerCountry = '$updateCountry',
postalCode = '$postalCode'
WHERE registerID = '$registerID'";
$updateResult = mysqli_query($mysqli,$updateQuery);
header("Location: profileUser");
}
}
After I updated, it still doesn't work after I am using prepared statement. Any ideas?
Try executing the query first, saving it into a variable.
then, check if the query executed by doing:
if(!$query) echo "Query error : " . $mysqli->error;
This will give you more detailed error report.
I'm pretty new to both PHP and MySQL and I'm struggling to get my login system to function properly. The registration works fine, but when I run the login it doesn't recognise there is anything within the table matching the entered data. Below is the code I believe to be the problem area.
Thanks in advance.
<?php
function load($page = 'login.php')
{
$url = 'http://'.$_SERVER['HTTP_HOST'].
dirname($_SERVER['PHP_SELF']);
$url = rtrim($url,'/\/');
$url.= '/'.$page;
header("location:$url");
exit();
}
function validate($dbc,$email ='',$pwd='')
{
$errors = array();
if (empty($email))
{ $errors[] = 'Enter your email address.'; }
else
{ $e = mysqli_real_escape_string($dbc,trim($email));}
if (empty($pwd))
{ $errors[] = 'Enter your password.';}
else
{ $p = mysqli_real_escape_string($dbc, trim($pwd)); }
if (empty($errors))
{
$q = "SELECT adultID, FirstName, Surname "
. "FROM adult_information "
. "WHERE Email = '$e' AND Password = SHA1('$p')";
$r = mysqli_query($dbc, $q);
if (mysqli_num_rows($r) == 1)
{ $row = mysqli_fetch_array($r, MYSQLI_ASSOC);
return array( true, $row);}
else
{$errors[]='Email address and password not found.';}
}
return array(false,$errors);
}
I believe that you'll get what you're looking for if you change
$q = "SELECT adultID, FirstName, Surname "
. "FROM adult_information "
. "WHERE Email = '$e' AND Password = SHA1('$p')";
to
$p = SHA1($p);
$q = "SELECT adultID, FirstName, Surname "
. "FROM adult_information "
. "WHERE Email = '$e' AND Password = '$p'";
Whenever a PHP-to-MySQL query isn't performing as expected, my first step is to get a look at the SQL I'm actually passing to the database. In this case, it would be by inserting a line like echo '<p>$q</p>'; immediately after assigning the value of $q.
Sometimes it immediately becomes obvious that I've got a malformed query just by looking at it. If it doesn't, I copy the SQL code that appears and run it as a query within the database manager, to see what errors it throws and/or examine the resulting data.