I'm trying to apply the finishing touches on a register form. I want to check if the user already has an account, based on his e-mail address. However, the PHP won't help me out. Here is the main part of my code.
$s = oci_parse($conn, "SELECT * FROM users WHERE mail='&mail'");
oci_execute($s);
$rows = 0;
while (oci_fetch($s))
{
$rows ++ ;
}
echo $rows; -> this echos all the time 0 even if I have 10+ registered users with same email
if($rows > 0)
{
//has account
}
else{
doesn't have account, inserting into DB
}
It seems like the value of $rows is always 0, no matter what I Do. I also tried with
SELECT COUNT(*) FROM users WHERE mail='$mail'
But i was unable to pass the correct value to the $rows variable.
Everything else works fine in my php code.
Thanks in advance
The error comes from the sql statement you have written &mail insted of $mail.
And by the way to count your rows you can use the function oci_num_rows($s) with this function you dont have to use the while loop
Related
I have an issue with an if logic statement that I cant seem to figure out and am looking for someone wiser than me to point out the error of my ways.
Below is my code:
$sql = "select count(id) from tempaddress where postcode='".$values['PostCode']."'";
$rs = CustomQuery($sql);
$data = db_fetch_array($rs);
print_r($data);
if ($data > 0)
{
//Redirect to Address Selection Page
$cid=$keys['CompanyId'];
header("Location: UpdateAddress_edit.php?editid1=".$cid);
exit();
}
else echo "<script>alert('No Addresses Found. Please Contact Administrator')</script>";
What this is supposed to do is look up how many results are found and if the answer is >0 then it takes it to next page, if not it gives you a popup message.
The count function works, but for some reason, even if the result is 0, it still takes the process to next page, see here http://prntscr.com/58949d, I have put a false post code in, and it should say, no!
Can anyone see what is going wrong, or point out a way to use if record exists then {}?
I am using PHP with MS Access.
Firstly, alias your expression:
$sql = "select count(id) as addressCount from tempaddress where postcode='".$values['PostCode']."'";
Then use it in the if statement
if ($data['addressCount'] > 0){
...
}
else{
}
try if($data[0] > 0 )since you're fetching as array
It should be like -
if ($data['Expr1000'] > 0)
I’m very new to the whole MySQLi thing. I have a basic understanding of PHP. Anyway, I’ve searched around here and just haven’t been able to get a solid answer.
Basically, I have a form where a person can enter name, email and promo code. The form validates the name and email but when it comes to the promo code, that’s where I’m getting stuck.
I have a database that has two columns. One is for the codes and the other is for a “used” column – eventually I need to be able to write a “1” to that column when a unique code has been used so it cannot be used again. I’m trying to use some code I found on here, FYI.
Here is the PHP (after connecting) to the database:
if(isset($_POST['sponsorcode']) && !empty($_POST["sponsorcode"])){
$sponsorcode = mysqli_real_escape_string($link,$_POST['sponsorcode']);
$query = "SELECT 'sponsorcode' FROM 'teachercodes' WHERE sponsorcode = '$sponsorcode'";
$result = mysqli_query($link, $query) or die(mysqli_error($link));
$option = "";
if(mysqli_num_rows($result)>0){
while($row=mysqli_fetch_array($result)) {
$option = "<option value='{$row['codes']}'>{$row['codes']}</option>";
}
Any tips would be GREATLY appreciated! Thanks.
No reason to perform your task as two separate steps. Simply mark the sponsor code as used in the teachercodes table. If the update affected any rows (i.e. mysqli_affected_rows returns 1 or more) then it hasn't been used before and is a valid sponsor code. Something like this:
// Make sure a sponsor code was provided
if (isset($_POST['sponsorcode']) && !empty($_POST['sponsorcode'])) {
// Escape the sponsor code to prevent SQL injection
$code = mysqli_real_escape_string($link, $_POST['sponsorcode']);
// Mark sponsor code as used if possible
$sql = 'UPDATE teachercodes SET used=1 WHERE sponsorcode="' . $code . '"';
mysqli_query($link, $sql) or die(mysqli_error($link));
if (mysqli_affected_rows($link)) {
// Sponsor code hasn't been used before and is valid
}
}
So here's my problem :
I have different queries on a same PHP page (SELECT queries). Each of these queries work fine separately (I have tested them).
These queries are used to make html tables and then to display graphs with a jquery plugin (the users are able to choose the graphs that they want to display on the page thanks to check-boxes).However, I can display only one graph because there's only one query that works when I refresh the page. The others return no result. I have tried using the function NextRowset() with a do-while but it doesn't work (even though there is no error)
Here is a part of my code so that you can see :
foreach($_POST['choixCourbe'] as $choixCourbe) {
if ($choixCourbe=='courantBatterie') {
$sql = 'SELECT batteryCurrent FROM data ORDER BY id'
$stmt = $bdd->prepare($sql1);
$stmt->execute();
do {
$rows = $stmt->fetchAll(PDO::FETCH_BOTH);} while ($stmt->nextRowset());
if ($rows == false) { echo 'No result';}
else { /*create table*/ }
$stmt->closeCursor();
}
if ($choixCourbe=='courantSolaire') {
$sql = 'SELECT sunCurrent FROM data ORDER BY id';
$stmt = $bdd->prepare($sql);
$stmt->execute();
do {
$rows = $stmt->fetchAll(PDO::FETCH_BOTH);} while ($stmt->nextRowset());
if ($rows == false) {echo 'No result';}
else {/*create table*/}
$stmt->closeCursor();
}
}
On the code above, the user should be able to see two graphs when he clicks on the two corresponding check-boxes (I have checked that both values of the check-boxes are correctly taken into account so that's not the problem) but there's currently one graph.
Any idea of what the problem is ?
Thanks for your answers,
Sophie
As far as I can see, the problem is as silly as two contradicting conditions,
if ($choixCourbe=='courantBatterie') {
and
if ($choixCourbe=='courantSolaire') {
of which only one can be executed at a time, obviously.
So, the problem is rather HTML related. make your checkbox names like choixCourbe[] and then use in_array() in PHP to test if particular value were selected.
I've built a contest system for a website, how it works is a user logs in, submits a ballot based on a real life event (sale of a particular object), and then at the end of the month, a random ballot is chosen and the owner of that ballot is the winner.
I've been asked to create a script which will email all users in the database the current amount of ballots they have in the system.
My current login/registration system is a heavily edited version of HTML-Form-Guies Simple PHP Registration System.
I know the pseudo code for what I want to do.
Step by step, the method needed goes like this.
Call on EmailUsersTotalEntries, populates an array with all the users in the database, pick the first entry in the array, user 1, find the sum of the all the rows in the itemsold column with the userid 1. then send user one an email with the results of the select sum(itemsold) from ballots where userid = 1; to user 1. Then the loop goes to user 2 and does the same thing, until it has sent an email to every user in the database.
Here are a few of the methods that I have either written or that are from the login system that will be used to accomplish this. My only problem is I dont know how to make a loop so that it will start from user 1 and then keep going all the way to user 2, and I dont know how to query the database for the user_id of whatever user the database/loop is currently on.
Methods are as follows:
This is the main method, it will call sub methods to collect the users and then send the actual email. I'm not sure if TotalEntries should be an array or not
function EmailTotalEntries()
{
if(empty($_POST['email']))
{
$this->HandleError("Email is empty!");
return false;
}
$user_rec = array();
if(false === $this->GetUsers($user_rec))
{
return false;
}
**/* $TotalEntries = array(); */**
if(false === $this->GetTotalEntriesForEmail($user_rec, $TotalEntries)
{
return false;
}
//At this point, I have an array, user_rec, populated with all the data from my users table, and an array $TotalEntries that will have nothing since its trying to pull from user_rec, which usually is one user but right now is all of the users.
//This is where I know I should have already started the loop, so chosen the first element in user_rec, and applied the GetTotalEntriesForEmail method, then the SendUserEmail method, then gone to the top of the loop and gone to the second user_rec element and repeat.
if(false === $this->SendUsersEmail($user_rec, $TotalEntries))
{
return false;
}
return true;
}
This is the method that collects the users
function GetUsers(&$user_rec)
{
if(!$this->DBLogin())
{
$this->HandleError("Database login failed!");
return false;
}
$result = mysql_query("Select * from $this->tablename",$this->connection);
$user_rec = mysql_fetch_assoc($result);
return true;
}
Here is the method I wrote to get the TotalEntries for a user that is logged in (checking his control panel to see how many entries he has)
function GetTotalEntries()
{
if(!$this->CheckLogin())
{
$this->HandleError("Not logged in!");
return false;
}
$user_rec = array();
if(!$this->GetUserFromEmail($this->UserEmail(),$user_rec))
{
return false;
}
$qry = "SELECT SUM(itemsold) AS TotalEntries FROM entries WHERE user_id = '".$user_rec['id_user']."'";
$result = mysql_query($qry,$this->connection);
while($row = mysql_fetch_array($result))
{
echo $row['TotalEntries'];
}
}
And here is how I believe it needs to be adapted to work in the email.
function GetTotalEntriesForEmail($user_rec, &$TotalEntries)
{
if(!$this->DBLogin())
{
$this->HandleError("Database login failed!");
return false;
}
$qry = "SELECT SUM(itemsold) FROM entries WHERE user_id = '".$user_rec['id_user']."'"; //$user_rec['id_user'] should the be id of the user the loop is currently on.
$result = mysql_query($qry,$this->connection);
$TotalEntries = mysql_fetch_assoc($result);
return true;
}
Heres the actual email
function SendUsers($user_rec, $TotalBallots)
{
$email = $user_rec['email']; //should be the for the user the loop is currently on.
$mailer = new PHPMailer();
$mailer->CharSet = 'utf-8';
$mailer->AddAddress($email,$user_rec['name']); //user the loop is currently on.
$mailer->Subject = "Total Ballots to Date";
$mailer->From = $this->GetFromAddress();
$mailer->Body ="Hello ".$user_rec['name']."\r\n\r\n". //Same thing
"To date you have: "/* .$TotalBallots. */" ballots.\r\n" //Same thing
if(!$mailer->Send())
{
return false;
}
return true;
}
I'm not very good at PHP, and this whole thing is a learning experience for me, so help is greatly appreciated.
If I havent been clear, maybe giving an example in another language would be clearer, so heres what I want to do, but in java
for(x = 0; x <= user_rec.length; x++)
{
int ballots = getTotalEntriesForUser(x);
sendEmailToUser(ballots)
}
If I havent been clear enough, please let me know and I will try to clarify as best as possible.
How can I combine the above code with a loop that will send all users an email, one by one, each email unique to the user it is sent to?
Are your functions part of a class? You wouldn't necessarily need them to do this. Here's my recommendation, which you can turn into functions, or a class, if you want. Also, you may want to consider looking into, and using MySQLi, and taking advantage of the classes it uses. Again, all just my recommendations.
Without knowing your table structure, I'm just taking a guess at this.
$sql = mysql_query("SELECT u.*,
u.user_id AS user,
COALESCE(SUM(e.itemssold), 0) AS total_items
FROM users u
LEFT JOIN entries e ON e.user_id = u.user_id
GROUP BY u.user_id");
while($row = mysql_fetch_array($sql))
{
$user = $row['user'];
$email = $row['user_email'];
$items = $row['total_items'];
yourEmailFunction($email, $items);
}
This pulls information from your users table, and your entries table based on matching User ID's. It sets the User ID from the user table as user so you don't have to try and distinguish between the two later. To learn about the COALESCE function, read here. The while() function will loop through every user it pulls from that SQL statement.
This hasn't been tested in any way, but that's basically what you need. Just pass the User's email, and the total Items, and write your email function to send that info to that email address.
However, if you know your functions work properly, and want to use a for loop, such as the one you provided in Java, here's how you'd write it in PHP.
for($x = 0; $x <= count($user_rec); $x++)
{
$ballots = getTotalEntriesForUser($x);
sendEmailToUser($ballots);
}
I'm developing a simple LAMP app where users can credit their account using Paypal. I suspect this is a simple issue, but have spent quite a while experimenting to no avail and would appreciate any thoughts:
System has a user management system working fine using sessions, but I can't get it to display the current user's credit.
But I've been trying things along the lines of:
$result = mysql_query("
SELECT *
FROM users
INNER JOIN account
ON account.UserID=account.UserID
ORDER BY account.accountID");
while($_SESSION['Username'] = $row['Username'] )
{
echo $row['Username'];
echo $row['Credit'];
}
I suspect the while statement is invalid, but I want it to echo username and credit where the current session username = the username stored in the database.
Thanks so much for taking a look - very much appreciated.
Okay there is actually a lot wrong with your code that can not be fixed by you as you have obviously no knowledge of php at all.
But let me explain this so you can get a good understanding of what you did wrong:
First of all, your mysql statement is just wrong.
Why do you join a field on itself? You won't get the corresponding users <-> account rows because users is never actually joined.
In addition to that, if you want to fetch a single row (you only want one because you only want to echo the data of one user, fetching more is only heavier in resources), tell mysql to do that. A simple example would be "WHERE a="b" LIMIT 1 (select only row where a is equal to "b", return after finding the first).
Now, to read something from your query, you need to fetch the corresponding data.
You can do that by using mysql_fetch_assoc / mysql_fetch_array / mysql_fetch_object.
This would look something like this: $data = mysql_fetch_array($query);.
In this case, you don't need to use a while() loop as you only have one row. A while loop is only necessary if you want to work with more then one row.
The rest of your code would be correct, though you don't need to call echo twice. You can simply connect both variables with a ".": echo $row['Username'].$row['Credit'];.
If you want to insert a space in between, connect it with another dot: echo $row['Username']." ".$row['Credit'];.
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
if ($row['Username'] == $_SESSION['Username'])
{
echo $row['Username'];
echo $row['Credit'];
break; // I believe username is unuque.
}
}
But it's much better to get just 1 row from the table :
$result = mysql_query("
SELECT *
FROM users
INNER JOIN account
ON account.UserID=users.UserID
WHERE Username ='".mysql_real_escape_string($_SESSION['Username'])."'" );
if ($result && $row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo .....
}
You only have a mysql result, now you have to return that information as an associative array (or object)
while ($row = mysql_fetch_assoc($result)) {
if ($_SESSION['username'] == $row['Username']) {
echo $row['Username'];
echo $row['Credit'];
}
}
It appears as if you are using $_SESSION['username'] as a way to check user authentication on the site, much better to use a salted+hashed version of the username and possibly the login time (never include the password).
One thing that jumps out at me is that your query is joining on:
account.UserID=account.UserID
instead of:
account.UserID=user.ID
Also, this is not right:
while($_SESSION['Username'] = $row['Username'] )
The = sign is for assignment, not comparison, so you're actually setting the value of $_SESSION['Username'] to $row['Username']. Then, the expression is evaluated as a boolean (since it's within a while conditional), and if it's true once, it'll be true forever. Infinite loop city.