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.
Related
How can i limit the failed logins with this script? If the login fails, i insert it into the sql. (Is it the right way?)
But how can i check at the next login, that the user can now log in? I would take the login limit in 1 hour.
Aniway, is this code is good for that?
<?php
$loginError = array();
if(isset($_POST['login_submit']))
{
if(empty($_POST['email']) or !isset($_POST['email'])){$loginError[] = "Hiányzó email cím.";}
if(empty($_POST['pass']) or !isset($_POST['pass'])){$loginError[] = "Hiányzó jelszó.";}
if(strlen($_POST['email']) > 50 ){$loginError[] = "Hibás adat az email mezőben.";}
if(strlen($_POST['pass']) > 40 ){$loginError[] = "Hibás adat a jelszó mezőben.";}
if(count($loginError) == 0 )
{
$email = mysqli_real_escape_string($kapcs,$_POST['email']);
$pass = sha1($_POST['pass']);
$lekerdezes = mysqli_query($kapcs, "SELECT * FROM admin_user WHERE email = '$email'") or die(mysqli_error($kapcs));
if(mysqli_num_rows($lekerdezes) > 0 )
{
$adat = mysqli_fetch_assoc($lekerdezes);
if($adat['status'] == 1 )
{
if($adat['pass'] == $pass)
{
$_SESSION['adatok'] = $adat;
$_SESSION['email'] = $adat['email'];
$_SESSION['userid'] = $adat['id'];
header("Location:home.php");
}
else
{
$sql = "INSERT INTO loginattempts(log_address, log_datetime) VALUES ('".$_SERVER['REMOTE_ADDR']."', NOW())";
$insert_login_attempt = mysqli_query($kapcs, $sql) or die(mysqli_error($kapcs));
$loginError[] = "Hibás email cím vagy jelszó.";
}
}
else
{
$sql = "INSERT INTO loginattempts(log_address, log_datetime) VALUES ('".$_SERVER['REMOTE_ADDR']."', NOW())";
$insert_login_attempt = mysqli_query($kapcs, $sql) or die(mysqli_error($kapcs));
$loginError[] = "Még nincs aktiválva a fiók.";
}
}
else
{
$sql = "INSERT INTO loginattempts(log_address, log_datetime) VALUES ('".$_SERVER['REMOTE_ADDR']."', NOW())";
$insert_login_attempt = mysqli_query($kapcs, $sql) or die(mysqli_error($kapcs));
$loginError[] = "Hibás email cím vagy jelszó.";
}
}
}
?>
I would create a field in the database called status (blocked/ok) and assuming youve got a field timestamp for the last login...
Then Id connect to the database in case the login fails and save the status bloqued and the time stamp. the next attempt you would check the time.now vs last access...
I good suggestion would be create a function for the database connection so you can call it a couple of time without repeat the code, also dont forget use the try/except fot the db connection.
I have the following PHP code which is for a voting system of an app.
Its a Q&A app, and the user can vote for questions and answers that are posted.
In my php code, I first check if the user has voted for a specific question.
This would exist in the QVOTES table, with the email and the id of the question being voted for.
When performing this check, I am not sure of how to see if $result is an empty set, so as to submit the user's vote if they have not voted for the question yet.
How can i get this working? All help is greatly appreciated.
<?php
$con=mysqli_connect("127.2.1.1","S837","887","D887");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$qid = $_POST['qid'];
$email = $_POST['email'];
$result = mysqli_query($con, "SELECT * FROM QVOTES WHERE QID = $qid AND EMAIL = '$email'");
if (!mysqli_num_rows($result) ){
if ($result = mysqli_query($con, "INSERT INTO QVOTES (QID, EMAIL) VALUES ($qid, '$email')")) {
mysqli_query($con, "Update QUESTIONS SET VOTES = VOTES +1 WHERE QID = $qid");
echo "Update successful";
} else{
echo "Update unsuccessful";
}
} else{
echo "null";
}
mysqli_close($con);
Actually you are doing in a wrong way. Please try to do like this:-
<?php
$con=mysqli_connect("127.2.1.1","S837","887","D887");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$qid = $_POST['qid'];
$email = $_POST['email'];
$result = mysqli_query($con, "SELECT * FROM QVOTES WHERE QID = $qid AND EMAIL = $email") or die(mysqli_error($con)); // no need of extra quote
if ($result->num_rows == 0 ){ // means no vote-up done till now
$result = mysqli_query($con, "INSERT INTO QVOTES (QID, EMAIL) VALUES ($qid, $email)")or die(mysqli_error($con)); // insert
if($result){
echo "Vote Added successfully.";
} else{
echo "Error occur while adding vote.Please try again.";
}
} else{
$result = mysqli_query($con, "Update QUESTIONS SET VOTES = VOTES +1 WHERE QID = $qid AND EMAIL = $email")or die(mysqli_error($con)); // upddate
if($result){
echo "Vote updated successfully.";
} else{
echo "Error occur while updating vote.Please try again.";
}
}
mysqli_close($con);
Note:- I change message for better understanding. You can change according to your wish. thanks.
How to see if $result is an empty set?
From the docs:
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE (Ref)
Use $result->num_rows if $result is not FALSE;
I'm building a php site where i want the user to create his company.
The script is checking if the user has any companies registered already and then it should display if he does or doesn't.
If he doesnt have a registered company, he should see a form where he can register.
If he choose to register a company the script will check for any company with the same name or insert the row.
My only problem is that when there's already a company with that name the echo doesnt display.
I have written inside the code where the problem is.
<?php
$con=mysqli_connect("mysql","USER","PASS","DB");
if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); }
$result_get_companies = mysqli_query($con,"SELECT * FROM companies WHERE userid='". $login_session ."' ORDER BY companyid ASC") or die(mysqli_error());
if (mysqli_num_rows($result_get_companies) >= 1) {
while($row_companies = mysqli_fetch_array( $result_get_companies )) {
$result_get_company_owner = mysqli_query($con,"SELECT username FROM users WHERE userid='". $login_session ."'") or die(mysqli_error());
$company_owner = mysqli_fetch_assoc($result_get_company_owner);
echo 'THIS WORKS';
}
} else {
if (isset($_POST['create_first_company']) && !empty($_POST['company_name'])) {
$company_name_unsafe = mysqli_real_escape_string($con, $_POST['company_name']);
$company_name = preg_replace("/[^a-zA-Z0-9\s]/","",$company_name_unsafe );
$check_companies = "SELECT companyid FROM companies WHERE company_name='". $company_name ."'";
$what_to_do_companies = mysqli_query($con,$check_companies);
if (mysqli_num_rows($what_to_do_companies) != 0) {
echo 'THIS DOESNT WORK
It does register that is should go here
because it does not insert new row.
and when the value is = 0 it does go
to else ELSE below and insert row.';
} else {
$result_create_company = mysqli_query($con,"INSERT INTO companies (companyname)
VALUES ('". $login_session ."')")
or die(mysqli_error());
echo 'THIS WORKS';
}
} else {
echo 'THIS WORKS!';
}
}
?>
I keep getting a 'Resource id # 6' failure when submitting a script on my website. The code I'm using is the same type of code I use for registering for the website and that works but this script doesn't work at all. What my code does is send a booking request with the fields as shown to the database. I keep getting a Resource id#6 error , and I've googled what that is but I can't seem to figure out whats wrong. I am a beginner at php , so any tips on whats to look for to avoid a resource id # 6 error would be a lot of help
<?php
//$pattern="/^.+#.+/.com/";
//error_reporting(0);
if(isset($_POST["submit"])){
$Name_of_Person = $_POST['Name_of_Person'];
$Name_of_Group = $_POST['Name_of_Group'];
$room = $_POST['room'];
$How_Many_People = $_POST['How_Many_People'];
$Date_of_Booking = $_POST['Date_of_Booking'];
$End_time = $_POST['End_time'];
$Purpose = $_POST['Purpose'];
$Contact_Number = $_POST['Contact_Number'];
$Contact_Email = $_POST['Contact_Email'];
$Alcohol = $_POST['Alcohol'];
$Security = $_POST['Security'];
$Projector = $_POST['Projector'];
$Extra_Chairs = $_POST['Extra_Chairs'];
$Extra_Info = $_POST['Extra_Info'];
$Activated = '0';
$con = mysql_connect('localhost','root','test123') or die("couldn't connect");
mysql_select_db('bookerdb') or die("couldn't connect to DB");
//if(filter_var($email, FILTER_VALIDATE_EMAIL)){//(preg_match($pattern, $_POST['Contact_Email'])){
$query = mysql_query("SELECT * FROM `booking_table` WHERE Date_of_Booking='".$Date_of_Booking."' AND room='".$room."'");
$numrows = mysql_num_rows($query);
echo $query;
if($numrows==0){
$sql="INSERT INTO `booking_table` (Name_of_Person,Name_of_Group,room,How_Many_People,Date_of_Booking,End_time,Purpose,Contact_Number,Contact_Email,Alcohol,Security,Projector,Extra_Chairs,Extra_Info, Activated) VALUES ('$Name_of_Person','$Name_of_Group','$room','$How_Many_People','$Date_of_Booking','$End_time','$Purpose','$Contact_Number','$Alcohol','$Security','$Projector','$Extra_Chairs','$Extra_Info',$Activated)";
$result = mysql_query($sql);
if($result){
echo "Sent to be approved";
$redirect_page = '../ASC.php';
$redirect = true;
if($redirect==true){
header('Location: ' .$redirect_page);
}
}else{
echo "Failed";
}
}else{
echo"There is already a requested booking on that date & time";
$redirect_page = '../EAR.php';
$redirect = true;
if($redirect==true){
header('Location: ' .$redirect_page);
}
}
/*}else{
echo "error";
$redirect_page = '../EWF.php';
$redirect = true;
if($redirect==true){
header('Location: ' .$redirect_page);
}
}*/
}
?>
You have error in your second SQL query. You try to insert 14 values into 15 columns (in values you forgot $Contact_Email).
$sql="INSERT INTO `booking_table` (Name_of_Person,Name_of_Group,room,How_Many_People,Date_of_Booking,End_time,Purpose,Contact_Number,Contact_Email,Alcohol,Security,Projector,Extra_Chairs,Extra_Info, Activated) VALUES ('$Name_of_Person','$Name_of_Group','$room','$How_Many_People','$Date_of_Booking','$End_time','$Purpose','$Contact_Number','$Contact_Email','$Alcohol','$Security','$Projector','$Extra_Chairs','$Extra_Info',$Activated)";
Than remove echo $query from your code, line 30.
In $query isn't query, but mysql result object. You can't work with that by this way, you can't echo it.
Simple PHP page (I'm no PHP expert, just learning) to update a MS SQL database. The following code generates an error that I dont know how to solve.
include '/connections/SFU.php';
$query = "UPDATE Person SET PhotoURL = '".$file["name"]."' WHERE USERID='".$_REQUEST['user_id']."';";
if ($result = odbc_exec($dbconnect, $query)) {
echo "// Success!";
}
else {
echo "// Failure!";
}
odbc_close($dbconnect);
//End Update
This fails every time in the "if ($result ..." section
However, if I run virtually the same code
include '/connections/SFU.php';
$query = "UPDATE Person SET PhotoURL = '89990.jpg' WHERE USERID='80'";
if ($result = odbc_exec($dbconnect, $query)) {
// Success!
}
else {
// Failure!
}
odbc_close($dbconnect);
//End Update
It works just fine. I have echoed the $query string to the screen and the string is the same for both. I can't figure out why it fails in one and not the other?
Also weird is when I use a parameterized query such as
include '/connections/SFU.php';
$query = "UPDATE dbo.Person SET PhotoURL=? WHERE USERID=?";
if ($res = odbc_prepare($dbconnect,$query)) {
echo "Prepare Success";
} else {
echo "Prepare Failed".odbc_errormsg();
}
$uid = $_REQUEST['user_id'];
$fn = $file["name"];
echo "query=".$query." userid=".$uid." filename=".$fn;
if ($result = odbc_exec($res, array($fn, $uid))) {
echo "// Success!";
}
else {
echo odbc_errormsg();
echo "// Failure!";
}
odbc_close($dbconnect);
The query fails in the prepare section above, but fails in the odbc_exec section below:
include '/connections/SFU.php';
$query = "UPDATE Person SET PhotoURL=? WHERE USERID=?";
if ($res = odbc_prepare($dbconnect,$query)) {
echo "Prepare Success";
} else {
echo "Prepare Failed".odbc_errormsg();
}
$uid = "80";
$fn = "samplefile.jpg";
echo "query=".$query." userid=".$uid." filename=".$fn;
if ($result = odbc_exec($res, array($fn, $uid))) {
echo "// Success!";
}
else {
echo odbc_errormsg();
echo "// Failure!";
}
odbc_close($dbconnect);
In all cases I do not get any odbc_errormsg ().
Remove the extra ; from your query.
$query = "UPDATE Person SET PhotoURL = '".$file["name"]."' WHERE
USERID='".$_REQUEST['user_id']."';";
^
So your query should be,
$query = "UPDATE Person SET PhotoURL = '".$file["name"]."' WHERE
USERID='".$_REQUEST['user_id'];
Also have practice of using odbc_errormsg() so you can have a better idea why your query gets failed.
Warning: Your code is vulnerable to sql injection attacks!