The problem I am facing is, mysql_num_rows gives me an output of 1 all through out the code, but when I match it wil 0 in an if statement, it returns true and does the code.
so $license returns ........ instead of its actual value.
I tried to debug the problem myself using these.
Tried print_r to see if datas exists. - Yes.
Tried echoing the $license at first part - returns the right value.
Tried checking the value of mysql_num_rows - returns 1.
Matching it with 0 in an if statement - returns true when it should be false since the value is 1.
Any help on this?
$check = mysql_query("SELECT * FROM licenses WHERE email='$email'") or die(mysql_error
());
if (mysql_num_rows($check) > 0)
{
while ($data = mysql_fetch_array($check))
{
print_r($data); // for test
$name = $data['name'];
$license = $data['pid'];
echo $license; // test print 1
$comments = $data['comments'];
}
if ($license == "Sgsmorgan")
$license = "EWP Discounted Basic (Simpleleveraging)";
}
$count = mysql_num_rows($check); // for test
echo $count; // returns 1.
if (mysql_num_rows($check) == 0)
$name = "";
$license = "...........";
echo $license;// test print 2
$comments = "Email doesnt exist in the database";
Surely you mean this:
if (mysql_num_rows($check)==0)
{
$name = "";
$license = "...........";
echo $license; //Test print 2
$comments = "Email doesnt exist in the database";
}
Rather than
if (mysql_num_rows($check)==0)
$name = "";
$license = "...........";
echo $license; //Test print 2
$comments = "Email doesnt exist in the database";
Not using the curly brackets means only the first line below the if statement is included within it. So $license is always set to ............
Always use curly brackets.
I believe that the issues is that, at that point, there are no more rows left, as your while loop has fetched all of them.
If I'm not mistaken, this code:
while ($ignored = mysql_fetch_array($check)) {
echo "Got a row! Rows left: " . mysql_num_rows($check);
}
Should output something like:
Got a row! Rows left: 3
Got a row! Rows left: 2
Got a row! Rows left: 1
Got a row! Rows left: 0
Following up on David's root-cause, here is a really simple fix:
$check = mysql_query("SELECT * FROM licenses WHERE email='$email'")
or die(mysql_error());
if (mysql_num_rows($check) > 0) {
while ($data = mysql_fetch_array($check)) {
$name = $data['name'];
$license = $data['pid'];
$comments = $data['comments'];
}
$license = ($license == "Blahblah") ? "This is a second level license" : $license;
} else {
$name = "";
$license = "...........";
$comments = "Email doesnt exist in the database";
}
Related
I'm trying to make a system where an administrator can add multiple people at the same time into a database. I want this system to prevent the administrator from adding people with email addresses already existing in the database.
IF one of the emails in the _POST["emailaddress"] matches with one of the emailaddresses in the db, the user should get a message saying one of the emails already exists in the database. To achieve this, I've tried using the function array_intersect(). However, upon doing so I get a warning saying:
Warning: array_intersect(): Argument #2 is not an array in ... addingusers.php on line 41
At first i thought it had something to do with the fact my second argument was an associative array, so I tried the function array_intersect_assoc, which returns the same warning. How can I solve this?
The code on addingusers.php
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors',1);
$conn = mysqli_connect('localhost','*','*','*');
$condition = false; // this is for the other part of my code which involves inserting the output into db
$name = $_POST["name"];
$affix = $_POST["affix"];
$surname = $_POST["surname"];
$emailaddress = $_POST["emailaddress"];
$password = $_POST["password"];
//amount of emailaddresses in db
$checkquery2 = mysqli_query($conn, "
SELECT COUNT(emailaddress)
FROM users
");
$result2 = mysqli_fetch_array($checkquery2);
// the previously mentioned amount is used here below
for($i=0; $i<$result2[0]; $i++){
// the actual emails in the db itself
$q1 = mysqli_query($conn, "
SELECT
emailaddress
FROM
users
");
// goes through all the emails
$result_array1 = array();
while ($row1 = mysqli_fetch_assoc($q1)) {
$result_array1[] = $row1;
}
$query1 = $result_array1[$i]["emailaddress"];
}
// HERE LIES THE ISSUE
for($i=0; $i<count($emailaddress); $i++){
if (count(array_intersect_assoc($emailaddress, $query1)) > 0) {
echo "One of the entered emails already exists in the database...";
echo '<br><button onclick="goBack()">Go Back</button>
<script>
function goBack() {
window.history.back();
}
</script><br>';
$condition = false;
}
else{
$condition = true;
}
}
EDIT
as the comments point out, $query1 is indeed not an array it is a string. However, the problem remains even IF i remove the index and "[emailaddress]", as in, the code always opts to the else-statement and never to if.
$query1 is not an array, it's just one email address. You should be pushing onto it in the loop, not overwriting it.
You also have more loops than you need. You don't need to perform SELECT emailaddress FROM users query in a loop, and you don't need to check the intersection in a loop. And since you don't need those loops, you don't need to get the count first.
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors',1);
$conn = mysqli_connect('localhost','*','*','*');
$condition = false; // this is for the other part of my code which involves inserting the output into db
$name = $_POST["name"];
$affix = $_POST["affix"];
$surname = $_POST["surname"];
$emailaddress = $_POST["emailaddress"];
$password = $_POST["password"];
$q1 = mysqli_query($conn, "
SELECT
emailaddress
FROM
users
");
// goes through all the emails
$result_array1 = array();
while ($row1 = mysqli_fetch_assoc($q1)) {
$result_array1[] = $row1['emailaddress'];
}
$existing_addresses = array_intersect($emailaddress, $result_array1);
if (count($existing_addresses) > 0) {
echo "Some of the entered emails already exists in the database: <br>" . implode(', ', $existing_addresses);
echo '<br><button onclick="goBack()">Go Back</button>
<script>
function goBack() {
window.history.back();
}
</script><br>';
$condition = false;
}
else{
$condition = true;
}
Having a problem with the 2nd query. when it gets to mysql_fetch_row - it kicks back
mysqli_fetch_row() expects parameter 1 to be resource, boolean given
Now I have also tried fetch assoc. But that as well kicks back an error. I have tried doing the 2nd query with '$id' and without it, yet still nothing. I think i am missing something very obvious.
I have went through many of the common post on here that refer to the error I am given but still haven't found a solution.
$con1 = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
$con2 = mysqli_connect($dbhost,$dbuser2,$dbpass2,$dbname2);
// Check connections
if($con1)
{ echo("1st Connection Successful "); }
else
{ echo("1st Connection Failed "); }
if($con2)
{ echo("2nd Connection Successful "); }
else
{ echo("2nd Connection Failed "); }
//start first database query
$query = "SELECT id, email FROM ow_base_user ORDER by ID LIMIT 30";
$result = $con1->query($query);
while($row = $result->fetch_row()) {
$rows[]=$row;
$id = $row[0];
$email_row = $row[1];
$email_sub = substr($email_row, 0, 2);
if ( $email_sub == "dk" ) {
$email = "1"; }
elseif ( $email_sub == "sv" ) {
$email = "3"; }
elseif ( $email_sub == "no" ) {
$email = "4"; }
elseif ( $email_sub == "nl" ) {
$email = "5"; }
elseif ( $email_sub == "de" ) {
$email = "2"; }
elseif ( $email_sub == "fi" ) {
$email = "6"; }
else {}
if (isset($email)) {
//start 2nd database query
$query2 = "SELECT country_id FROM website_user WHERE userId = $id LIMIT 1";
$result2 = $con2->query($query2);
$row2 = mysqli_fetch_row($result2);
$country = $row2[6];
if (isset($country)) {
}
if (DEVMODE) {
echo "user id = ".$id." -- ";
echo "email = ".$email." -- ";
echo "COUNTRY = ".$country."<br />";
}
}
}
So changed the code around a bit to print out errors incase the query wasn't going through.
If($result2 === false) {
echo "error while executing mysql: " . mysqli_error($con2);
} else {
after adding this in I received the error.
mysqli_error() expects parameter 1 to be mysqli, null given
Ok so, these errors where caused by a typo in the databse table name thanks for pointing out the error report all method in the comments.
UPDATE: so after fixing the connection issue. I receive Notice: Undefined offset: 5 in $country = $row2[6];
UPDATE: after change $country = $row2[0]; - This solved the final issue.
for development build you can use
error_reporting(E_ALL);
ini_set('display_errors', 1);
which showed the database table was misspelled. after that, had to change the which row was being pulled since it was only 1 row, instead of all rows.
I have a query that should look for an entry. If it's not in the database then enter in the data. Otherwise it returns back the data and they can update any fields. If there is an entry it will be only one. This works great if the entry is in the table. But I've tried checking for empty rows, doing row_count, etc and doesn't seem to work. Right now I just have this in the code(sanitized to remove company table information):
$query1 = " SELECT Number, Notes, Qty1, Qty2 FROM test.notes ";
$query1 .= " WHERE Number = '$searchnumber' ";
$result1 = $conn1->query($query1);
$conn1 = null;
if($result1==null)
{
echo "Result is null</p>\n";
return 0;
}
else
{
echo "Result is not null</p>\n";
return $result1;
}
If I take out the if check what I seem to get back is if it's found it returns the values correctly. If it's not found the result seems to be the query string itself. The check doesn't work. Probably because it returns back the query string if it's not found.
I know it's something simple but just haven't found it.
// if available in database
$query="SELECT Number, Notes, Qty1, Qty2 FROM test.notes WHERE Number='".$searchnumber."'";
$qnt = $conn1->query($query);
$coun = count($qnt->fetchAll());
if($coun > 0){
// available
echo "Result is available</p>\n";
}else{
//not available
echo "Result is not available</p>\n";
}
i Think you need something like this.
if this is not working fine, try another aproach
$queryi = $conn1->prepare("SELECT Number, Notes, Qty1, Qty2 FROM test.notes WHERE Number='".$searchnumber."' ");
$queryi->execute();
$qn= $queryi->fetchAll(PDO::FETCH_ASSOC);
foreach ($qn as $row => $data) {
$in_use = $data['Number'];
//echo $in_use ;
}
// evaluate
if($in_use == NULL){
//not avilable
}else{
// available
}
I suggest doing something like this:
Establish your query
$query1 = " SELECT Number, Notes, Qty1, Qty2 FROM test.notes ";
$query1 .= " WHERE Number = '$searchnumber' ";
See if there's a result for the query, and no error
if ($res = $conn1->query($sql)) {
/* Check the number of rows that match the SELECT statement */
if ($res->fetchColumn() > 0) {
/* Issue the real SELECT statement and work with the results */
$sql = "SELECT name FROM fruit WHERE calories > 100";
foreach ($conn->query($sql) as $row) {
print "Name: " . $row['NAME'] . "\n";
}
}
/* No rows matched -- do something else */
else {
print "No rows matched the query.";
}
}
After some trial and error I got this to work:
$result1 = $conn1->query($query1);
$count = $result1->fetchColumn();
if($count == "")
{
// echo "Result is null</p>\n";
return "0";
}
else
{
// echo "Result is not null</p>\n";
$result1 = $conn1->query($query1);
return $result1;
}
I had to change the setup to include:
$conn1->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, TRUE);
Probably not a clean way but it works for now. Thanks for all the help.
There is ALOT of code, but most of it is irrelevant, so i will just post a snippet
$error_message = "";
function died($error) // if something is incorect, send to given url with error msg
{
session_start();
$_SESSION['error'] = $error;
header("Location: http://mydomain.com/post/error.php");
die();
}
This works fine, sends the user away with a error session, which displays the error on the error.php
function fetch_post($url, $error_message) {
$sql = "SELECT * FROM inserted_posts WHERE name = '$name'";
$result = mysqli_query($con, $sql);
$num_rows = mysqli_num_rows($result);
if ($num_rows > 0) {
$error_message .= $url . " already exists in the database, not added";
return $error_message;
}
}
This also works fine, checks if the "post" exists in the database, if it does, it adds the error the variable $error_message
while ($current <= $to) {
$dom = file_get_html($start_url . $current); // page + page number
$posts = $dom->find('div[class=post] h2 a');
$i = 0;
while ($i < 8) {
if (!empty($posts[$i])) { // check if it found anything in the link
$post_now = 'http://www.somedomain.org' . $posts[$i]->href; // add exstension and save it
fetch_post($post_now, &$error_message); // send it to the function
}
$i++;
}
$current++; // add one to current page number
}
This is the main loop, it loops some variables i have, and fetches posts from a exsternal website and sends the URL and the error_message to the function fetch_posts
(I send it along, and i do it by reference couse i asume this is the only way to keep it Global???)
if (strlen($error_message > 0)) {
died($error_message);
}
And this is the last snippet right after the loop, it is supposed to send the error msg to the function error if the error msg contains any chars, but it does not detect any chars?
You want:
strlen($error_message) > 0
not
strlen($error_message > 0)
Also, call-time pass-by-reference has been deprecated since 5.3.0 and removed since 5.4.0, so rather than call your function like this:
fetch_post($post_now, &$error_message);
You'll want to define it like this:
function fetch_post($url, &$error_message) {
$sql = "SELECT * FROM inserted_posts WHERE name = '$name'";
$result = mysqli_query($con, $sql);
$num_rows = mysqli_num_rows($result);
if ($num_rows > 0) {
$error_message .= $url . " already exists in the database, not added";
return $error_message;
}
}
Although as you're returning the error message within a loop it would be better to do this:
$error_messages = array();
// ... while loop
if ($error = fetch_post($post_now))
{
$error_messages[] = $error;
}
// ... end while
if (!empty($error_messages)) {
died($error_messages); // change your function to work with an array
}
I have output from a select query as below
id price valid
1000368 69.95 1
1000369 69.94 0
1000370 69.95 0
now in php I am trying to pass the id 1000369 in function. the funciton can execute only if the valid =1 for id 1000368. if it's not 1 then it will throw error. so if the id passed is 1000370, it will check if valid =1 for 1000369.
how can i check this? I think it is logically possible to do but I am not able to code it i tried using foreach but at the end it always checks the last record 1000370 and so it throws error.
regards
Use a boolean variable:
<?php
$lastValid=false;
while($row = mysql_fetch_array($result))
{
if ($lastValid) {
myFunction();
}
$lastValid = $row['valid'];
}
?>
(Excuse possible errors, have no access to a console at the moment.)
If I understand correctly you want to check the if the previous id is valid.
$prev['valid'] = 0;
foreach($input as $i){
if($prev['valid']){
// Execute function
}
$prev = $i;
}
<?php
$sql = "SELECT * FROM tablename";
$qry = mysql_query($sql);
while($row = mysql_fetch_array($qry))
{
if ($row['valid'] == 1)
{
// do some actions
}
}
?>
I really really recommend walking through some tutorials. This is basic stuff man.
Here is how to request a specific record:
//This is to inspect a specific record
$id = '1000369'; //**some specified value**
$sql = "SELECT * FROM data_tbl WHERE id = $id";
$data = mysql_fetch_assoc(mysql_query($sql));
$valid = $data['valid'];
if ($valid == 1)
//Do this
else
//Do that
And here is how to loop through all the records and check each.
//This is to loop through all of it.
$sql = "SELECT * FROM data_tbl";
$res = mysql_query($sql);
$previous_row = null;
while ($row = mysql_fetch_assoc($res))
{
some_action($row, $previous_row);
$previous_row = $row; //At the end of the call the current row becomes the previous one. This way you can refer to it in the next iteration through the loop
}
function some_action($data, $previous_data)
{
if (!empty($previous_data) && $condition_is_met)
{
//Use previous data
$valid = $previous_data['valid'];
}
else
{
//Use data
$valid = $data['valid'];
}
if ($valid == 1)
{
//Do the valid thing
}
else
{
//Do the not valid thing
}
//Do whatever
}
Here are some links to some good tutorials:
http://www.phpfreaks.com/tutorials
http://php.net/manual/en/tutorial.php