PHP IF condition on results of SQL Query - php

I want to send a mail using PHP Mailer, but first I need to validate 3 tables
This is the code I have,
//First I query the 2 tables to validate today's data and 3rd table to see if mail already sent
$verifyJobData = $dbconnection->query("SELECT id FROM [Jobs] WHERE date=CAST(GETDATE() AS DATE)");
$verifyJobData->fetchAll(PDO::FETCH_OBJ);
$verifyWIPData = $dbconnection->query("SELECT id FROM [WIP] WHERE date=CAST(GETDATE() AS DATE)");
$verifyWIPData->fetchAll(PDO::FETCH_OBJ);
$verifyDuplicateMail = $dbconnection->query("SELECT status FROM [Mail_Log] WHERE mailtype = 'DailyStatus' AND datesent = CAST(GETDATE() AS DATE) AND status = 1;");
$mailStatus = $verifyDuplicateMail->fetchAll(PDO::FETCH_OBJ);
$mailStatus=$mailStatus->status;
//On the first IF I want to validate that IF $mailStatus->status is different than 1 pass to the next IF to validate the other data
if ($mailStatus != 1) //Enter next IF
{
if ($verifyJobData->rowCount() && $verifyWIPData->rowCount())//The select had result continue to send code
{
echo "Code to send mail already working";
}
} else {
echo "Do not send mail and execute Code to insert failure status to DB also working";
}
The first IF is not validating the $mailStatus IF the value is 0, null or different than 1 also passes to the next IF.
This is what I tried, I did a lot of research but I am not finding what I need I might be searching wrong, also if you can share the URL to read the examples

Try this:
switch($mailStatus){
case 1:
echo "Do not send mail and execute Code to insert failure status to DB also working";
break;
default:
if ($verifyJobData->rowCount() && $verifyWIPData->rowCount()) {
echo "Code to send mail already working";
}
}

Related

Why does POST value save empty in database, but var_dumps / echos fine?

I have a contact list that I made with PHP, jQuery and Datatables, where I have inline editing, and as soon as you click outside of a cell it updates via Ajax. Everything about the update of field values work fine, but now I wanted to save who last updated a record, by saving the username from the current session, so I've done that and sent it to the update file as a $_POST, but it won't save. When I dump it out or echo it, I can see the value, so I know it does get posted, but it just won't save in the database and I can't figure out why.
Since I don't code a lot and have learned what I know by reading and copying stuff from Stackoverflow, I'm sure I'm missing something obvious, but I still need help and I want to learn.
I've tried all kinds of "' variants, and typing in "test" or something in the query or in the variable does save it, so I feel like something is wrong with the $_POST or sql syntax, but since I can dump it and echo it, I have no idea what's wrong.
Worth mentioning is that the first part of the SQL works fine, and updates the cell it's supposed to, so the query runs, but randomly returns either "Uppdaterad!" or "Invaild requests" every other time, but the value saves either way. If I remove the whole "new part" with "last updated by", it works every time and returns "Uppdaterad!" without any problems.
<?php
if(!empty($_POST))
{
// Database settings
include "config.php";
foreach($_POST as $field_name => $val)
{
// Clean post values
$field_contactid = strip_tags(trim($field_name));
$val = strip_tags(trim(mysqli_real_escape_string($con, $val)));
$currentuser = strip_tags(trim(mysqli_real_escape_string($con, $_POST['currentuser'])));
//var_dump($currentuser);
// From the fieldname:contact_id we need to get contact_id
$split_data = explode(':', $field_contactid);
$contact_id = $split_data[1];
$field_name = $split_data[0];
if(!empty($contact_id) && !empty($field_name))
{
// Update the values
mysqli_query($con, "UPDATE contactlist SET $field_name = '$val', `last_updated_by` = '$currentuser' WHERE id = $contact_id") or mysqli_error($con);
//mysqli_query($con, "UPDATE contactlist SET $field_name = '$val' WHERE id = $contact_id") or mysqli_error($con);
echo "Uppdaterad!";
} else {
echo "Invalid Requests";
}
}
} else {
echo "Empty POST!";
}
?>

Query isn't inserting into database [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 6 years ago.
I am attempting to implement a click count system. I am using the following code in this link Click here to see code, but changing it to modern standards. Initially I received errors for the msqli_real_escape_ string, but I believed I resolved it(no errors). Now, I am not receiving any errors at all, but the query is not sending into my database. I am using ini_set('display_errors', 1);
error_reporting(E_ALL); for error checking. Also I have my $con and session in and ini file that I call, so the session and connection are not issues.
Does anyone see what I am doing wrong or is there a good way I can check to see what isn't working?
//create current page constant
$curPage = mysqli_real_escape_string($con,htmlspecialchars($_SERVER['PHP_SELF']));
//set number of clicks variable to 0
$clicks = 0;
//do not recount if page currently loaded
if($_SESSION['page'] != $curPage) {
//set current page as session variable
$_SESSION['page'] = $curPage;
$click_sql = "
SELECT *
FROM click_count
WHERE page_url = ?
";
if (!$click_stmt = $con->prepare($click_sql)) {
$click_stmt->bind_param("s", $curPage);
$click_stmt->execute();
$num_rows = $click_stmt->fetchColumn();
if (!$click_stmt->errno) {
// Handle error here
}
$stmt->bind_result($click_id, $page_url, $page_count);
} elseif ($num_rows == 0) {
//try to create new record and set count for new page to 1
//output error message if problem encountered
$click_insert_stmt = "
INSERT INTO click_count
(page_url, page_count)
VALUES(?, ?)";
if(!$click_stmt = $con->prepare($click_insert_stmt)) {
$click_insert_stmt->execute(array('$curPage',1));
echo "Could not create new click counter.";
}
else {
$clicks= 1;
}
} else {
//get number of clicks for page and add 1 fetch(PDO::FETCH_BOTH)
while($click_row = $click_insert_stmt->fetch(PDO::FETCH_BOTH)) {
$clicks = $row['page_count'] + 1;
//update click count in database;
//report error if not updated
$click_update_stmt = "
UPDATE click_count
SET page_count = ?
WHERE page_url = ?
";
if(!$click_stmt = $con->prepare("$click_update_stmt")) {
$click_update_stmt->execute(array('$clicks', '$curPage'));
echo "Could not save new click count for this page.";
}
}
}
}
Edit: New Updated Code
// ********Page count************
//create current page constant
$curPage = mysqli_real_escape_string($con,($_SERVER['PHP_SELF']));
//set number of clicks variable to 0
$clicks = 0;
//do not recount if page currently loaded
if($_SESSION['page'] != $curPage) {
//set current page as session variable
$_SESSION['page'] = $curPage;
$click_sql = "
SELECT *
FROM click_count
WHERE page_url = ?
";
if (!$click_stmt = $con->prepare($click_sql)) {
$click_stmt->bind_param("s", $_SERVER['PHP_SELF']);
$click_stmt->execute();
$num_rows = $click_stmt->fetchColumn();
if (!$click_stmt->errno) {
// Handle error here
}
$stmt->bind_result($click_id, $page_url, $page_count);
} elseif ($num_rows == 0) {
//try to create new record and set count for new page to 1
//output error message if problem encountered
$click_insert_stmt = "
INSERT INTO click_count
(page_url, page_count)
VALUES(?, ?)";
if(!$click_stmt = $con->prepare($click_insert_stmt)) {
$click_insert_stmt->execute(array($curPage,1));
echo "Could not create new click counter.";
}
else {
$clicks= 1;
}
} else {
//get number of clicks for page and add 1 fetch(PDO::FETCH_BOTH)
while($click_row = $click_insert_stmt->fetch(PDO::FETCH_BOTH)) {
$clicks = $row['page_count'] + 1;
//update click count in database;
//report error if not updated
$click_update_stmt = "
UPDATE click_count
SET page_count=page_count+1
WHERE page_url = ?
";
if(!$click_stmt = $con->prepare("$click_update_stmt")) {
$click_update_stmt->execute(array($curPage));
echo "Could not save new click count for this page.";
}
}
}
}
It looks like you're doing a lot of stuff like this:
$click_update_stmt->execute(array('$clicks', '$curPage'));
I'm not sure where you picked up this habit of quoting variables as strings, but you need to drop it. '$x' and $x are two hugely different things. In the first case it's literally '$x' and in the second case it's whatever the $x variable happens to represent.
Fix it like this:
$click_update_stmt->execute(array($clicks, $curPage));
Also since you're using prepared statements, which by the way is great, you do not need to and should not manually escape your values. Applying them to placeholders with bind_param is the safe way of doing it. Doing any other escaping mangles the data.
Just bind directly to the source:
$click_stmt->bind_param("s", $_SERVER['PHP_SELF']);
Don't arbitrarily run things like htmlspecialchars on input out of paranoia or because you're doing cargo-cult programming and you saw it done in a YouTube tutorial somewhere. That function is intended to be used to display values only, not store them. Data in your database should be as raw as possible.
There's a lot of problems with this code, and one of them that has me confused is why there's so much code. Remember SELECT * and then binding results to arbitrary variables is trouble, your schema might change and then your code is out of sync. Whenever possible fetch rows as an associative array if doing this, then all you have to worry about is renamed ore removed columns.
The biggest problem is this is subject to race conditions because it doesn't use an atomic increment. When writing counters, always do your updates as operations that are a single statement:
UPDATE click_count SET page_count=page_count+1 WHERE page_url=?
Your approach of reading the count, incrementing it, and then writing it back into the database means that you're inviting problems if another operation runs concurrently, something very likely on click-counter code.

MySQL UPDATE return value

I started coding a simple script that reads IDs from CSV and then sets the same email address (in DB) for ALL users from CSV. Simple enough...(using PDO)
reading of data from CSV is ok. It's the update part that is giving me headaches.
$sSQL = "UPDATE users SET email = 'something#something.com' WHERE CUSTOMER_ID = '%s'";
foreach ($aUsers as $sCustomerId) {
$sQuery = sprintf($sSQL, $sCustomerId);
if (!$db->exec($sQuery)) {
printf("There was an error updating user %s in database.<br>", $sCustomerId);
$aFailed[] = $sCustomerId;
} else {
printf("User %s successfully updated.<br>", $sCustomerId);
$success++;
}
}
script is really easy. The problem is that mysql doesn't UPDATE the user in DB if he already has that email address so it will return 0 (0 rows affected which is ok). Which is also the same thing mysql returns if error occures during update. And that is what's driving me nuts. How do I distinguish between "no rows affected" and "error occured". I tried using different PDO::ATTR_ERRMODEs and was expecting that at least in the case of error it will throw an exception (which kind of PDO::ERRMODE_EXCEPTION should do) which I can than catch but it doesn't. Then I trid to use
if ($db->exec($sQuery) === FALSE)
also doesn't work. The script now works but the problem is that I can't distinguish "error" from "no affected rows".
Is that behavior in mysql new or? Because I can't remember having that problem in the past when writing such simple scripts for update...
Manual says: "If you set a column to the value it currently has, MySQL notices this and does not update it."
You probably could use errorCode() AND errorInfo() to identify an error.
errorCode() function returns NULL, if query has no problems.
Example:
$db->exec($sQuery);
if ($db->errorCode() !== NULL) {
// Additional error info from: $db->errorInfo()
printf("There was an error updating user %s in database.<br>", $sCustomerId);
$aFailed[] = $sCustomerId;
} else {
printf("User %s successfully updated.<br>", $sCustomerId);
$success++;
}
PHP documentation:
http://php.net/manual/en/pdo.errorcode.php
http://php.net/manual/en/pdo.errorinfo.php
If you are using PDO, try to do prepare and then execute, which returns true on success, false on error
$sSQL = "UPDATE users SET email = 'something#something.com' WHERE CUSTOMER_ID = :customer_id";
$sth = $db->prepare($sSQL);
if(!$sth->execute(array(':customer_id' => $sCustomerId)))
{
printf("There was an error updating user %s in database.<br>", $sCustomerId);
} else {
printf("User %s successfully updated.<br>", $sCustomerId);
}
It's a good pratice for keeping your script secure. Execute will bind params, so there is no need to escape or quote them.

PHP Checking if specify entered Email & Id are matching to the ones in the database

I have recently switched from Mysql_* to PDO, heard it's the new, better more secure way of connecting and working with MySQL databases.
I have learned many basics of it like queries, prepare, etc.
What do I want to do
I currently have two text fields, named 'Email' and 'ID'.
When user registers, he enters his email, after he registers he receives his own ID, something unique.
I want him to be able to check the status of his account, without any passwords.
Simply by entering his email, and id and clicking 'submit'.
After clicking submit, the system should check if there's a column with the same email & ID.
If there is a column with these same exact email & IDs, then I can create a while loop to grab information from his account's column like creation date, and others..
My Question
How would I do this?
There's what I've done so far:
if (isset($email) && isset($id) && isset($submit)) {
$fetch = $connect->prepare("SELECT * FROM users WHERE email = :email LIMIT 1");
$fetch->bindValue(':email', $email);
$fetch->execute();
$validate = $fetch->fetchColumn();
if ($validate == 0) {
echo 'failed';
} else {
echo 'not failed';
}
while($row = $fetch->fetch( PDO::FETCH_ASSOC )) {
//We can fetch here...
}
}
My friend suggested me to use fetchColumn() which is replacing mysql_num_columns function, but It doesn't seem to work.
I enter a right email address, and it is still echoing 'Failed' instead of 'Not failed'.
Why doesn't this method work? Have I done this wrong?.
Thanks!
I don't think you want to fetch columns, but rows. You also don't actually check the ID either, but you can just add an AND condition to your query if necessary.
$fetch->execute();
if ($fetch->rowCount()) {
echo "Row was returned; match found";
}
else {
echo "No match found";
exit;
}
$row = $fetch->fetch(PDO::FETCH_ASSOC);
There will probably only be one row for you to fetch as well, but in case there aren't you can use the while loop as you did above.
$validate is a string containing the email address. When doing if ($validate == 0) you're typecasting $validate to an integer, and any non-numeric string becomes (int) 0, and so the comparison is always true.
Change to if ($validate === FALSE).

Insert multiple data as well as update in database using php?

I get Nearest 50 km location names from current location using google api, so it' works fine.
So I need to insert all these locations into my database. If some location already there in database, I need to update these location.
For example I get 10 locations in google api so 5 locations are already there in my database. I need to 5 location are update and remaining 5 locations are insert.
Here is my code:
<?php
require 'dbconnect.php';
$LocaName=$_REQUEST['locname'];
$address=$_REQUEST['address'];
$latt=$_REQUEST['Latt'];
$long=$_REQUEST['Long'];
if($latt && $long)
{
$LocaNamearray = explode("|||", $LocaName);
$addressarray = explode("|||", $address);
$lattarray=explode("|||",$latt);
$longarray=explode("|||",$long);
for($i=0;$i<count($lattarray);$i++)
{
$query1="select * from tbl_MapDetails where Latitude='".$lattarray[$i]."'and Longitude='".$longarray[$i]."'";
$result1=mysql_query($query1);
$now=mysql_num_rows($result1);
}
if($now >=1)
{
for($k=0;$k<count($lattarray);$k++)
{
$query="update tbl_MapDetails set LocationName='".$LocaNamearray[$k]."', Address='".$addressarray[$k]."',Latitude='".$lattarray[$k]."', Longitude='".$longarray[$k]."' where Latitude='".$lattarray[$k]."'and Longitude='".$longarray[$k]."'";
}
$nav="update";
}
else
{
$query ="INSERT INTO tbl_MapDetails(LocationName,Address,Latitude,Longitude) VALUES";
$strDelimiter = "";
for($j=0;$j<count($LocaNamearray);$j++)
{
$name =$LocaNamearray[$j];
$address =$addressarray[$j];
$lat = $lattarray[$j];
$long = $longarray[$j];
$query .= $strDelimiter."('$name', '$address','$lat','$long')";
$strDelimiter = ',';
}
$nav="Add";
}
$result= mysql_query($query);
if($result)
{
echo mysql_error();
$message=array("message"=>"sucessfully".$nav);
}
else
{
echo mysql_error();
$message=array("message"=>"fail".$nav);
}
}
else
{
$message=array("message"=>"require latt and long");
}
echo json_encode($message);
?>
Here insert and update working but I need to check every location in database. There is no location in database. It need to insert other location are update. how to check both these conditions matched locations are update and unmatched locations are inserted Please guide me.
Your logic is wrong in the code. What you are doing is looping through the provided data and for each set of data checking if a location with that lat/long exists and storing it in the $now variable. Once you've finished that loop, you're then checking $now and looping through the provided data again and either INSERTing or UPDATEing each set of data. So if the last set of data exists, your script will try and UPDATE each set of data. If it doesn't, your script will try to INSERT each set of data. Your code should be something like this (mixture of your code and pseudo-code):
for($i=0;$i<count($lattarray);$i++)
{
$query1="select * from tbl_MapDetails where Latitude='".$lattarray[$i]."'and Longitude='".$longarray[$i]."'";
$result1=mysql_query($query1);
$now=mysql_num_rows($result1);
if($now >=1)
{
// update table with location details
}
else
{
// insert location details into table
}
}
If this becomes a performance issue you could look at retrieving all the SELECT data first but if you're only dealing with 10 rows at a time you should be OK.
Note: depending on where your $_REQUEST data is coming from you might want to do some validation, i.e. to check you have matching sets of lat/long/name/address details.
Take a look at MySQL`s ON DUPLICATE KEY UPDATE. But you must be careful, because it is quite slow operation.
But, I think, it would be better if you just union all your SELECT requests in one using OR conditions.

Categories