Problem with 2 database queries and fetching data from row - php

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.

Related

Find method in SQL on my PHP page finds everything, even if the record is null

Ok so I wrote some code to find records on a test database, it works if there is a record and does display the data, if there is no record it still says that it found stuff. It should say it did not. It even finds stuff that is not in the database but obviously has no data to display, its annoying.
I need a new pair of eyes.
I think the error is here:
$sql = "SELECT * FROM Kittenzz
WHERE KittenID='".$_POST['KittenID']."';";
$result = mysql_query($sql, $connection);
But just in case here is the full code minus the login credentials to the db.
<?php
if(isset($_POST['Find']))
{
$connection = mysql_connect("Login Info Deleted");
// Check connection
if (!$connection)
{
echo "Connection failed: " . mysql_connect_error();
}
else
{ //else 1
//select a database
$dbName="Katz";
$db_selected = mysql_select_db($dbName, $connection);
//confirm connection to database
if (!$db_selected)
{
die ('Can\'t use $dbName : ' . mysql_error());
}
else
{ //else 2
if ($_POST[KittenID]=='')
{
$OutputMessage = 'Must add a Kitten-ID';
}
else
{//exception else
$sql = "SELECT * FROM Kittenzz
WHERE KittenID='".$_POST['KittenID']."';";
$result = mysql_query($sql, $connection);
while($row = mysql_fetch_array($result))
{
$Name = $row['Name'];
$KittenID = $row['KittenID'];
$KittenAge = $row['KittenAge'];
$Email = $row['Email'];
$Comments = $row['Comments'];
$Gender = $row['Gender'];
$Passive = $row['Passive'];
$Playful = $row['Playful'];
$Activity = $row['Activity'];
}
if ($result)
{
$OutputMessage = 'Record Found';
//echo "<p>Record found<p>";
}
else
{
$OutputMessage = 'RECORD NOT FOUND';
}
}//exception else
}//else 2 end
}//else 1 end
mysql_close($connection);
}
?>
if ($result)
{
$OutputMessage = 'Record Found';
}
There is your mistake, that means if the query executed successfully (even with 0 records) you are saying records found. You should only say that if the number of records returned are more than 0.
if (mysql_num_rows($result)>0)
{
$OutputMessage = 'Record Found';
}
But the bigger problem with your code can be solved by this reading
How can I prevent SQL injection in PHP?
This may happen, because if $_POST['KittenID'] is empty, the sql query would look like : SELECT * FROM Kittenzz WHERE KittenID=""; you have to change the above if statement to:
if (!isset($_POST[KittenID]) || empty($_POST[KittenID]) || $_POST[KittenID]=='')
{
$OutputMessage = 'Must add a Kitten-ID';
}

[function.mysql-result]: Unable to jump to row 0 on MySQL result index 3 in subscribe.php on line 54

I have a error in my newsletter and I don't know what doing wrong. Please help me.
Now I doing newsletter, first time I used MySQL in my code.
Here is the error:
Warning: mysql_result() [function.mysql-result]: Unable to jump to row 0 on MySQL result index 3 in subscribe.php on line 54
Here is my code:
if($mail == NULL){
}
else{
$token = sha1(time());
$result1 = #mysql_query("INSERT INTO newsletter (Address,Token) VALUES (\"".$mail."\", \"".$token."\") ");
if ($result1) {
sendmail($mail);
}
else{ /*This else */
$result2 = mysql_query("SELECT Confirmed FROM newsletter where Address = \"".$mail."\" ");
$confirm = mysql_result($result2,0);
if($confirm == "y"){
}
else if($confirm == "n"){
}
}
}
?>
What I do wrong?
You could try:
(...)
else{ /*This else */
$result2 = mysql_query("SELECT Confirmed FROM newsletter where Address = \"".$mail."\" ");
if($row = mysql_fetch_array($result2)) {
$confirm = $row["Confirmed"];
}
else {
$confirm = "n"; // Returned 0 rows
}
$confirm = mysql_result($result2,0);
if($confirm == "y"){
}
else if($confirm == "n"){
(...)

trying to convert mysql select statement to PDO

I'm trying to convert from an old MySQL library to PDO.
In order to read the data with my old MySQL code I use:
$assoc = mysql_fetch_assoc($exeqr);
With PDO I'm trying to do that with a foreach like I have on my code using PDO, but its not working...
Can you see something wrong here??
My OLD ode using MySQL:
<?php
if(isset($_POST['sendLogin']))
{
$f['email'] = mysql_real_escape_string($_POST['email']);
$f['pass'] = mysql_real_escape_string($_POST['password']);
if(!$f['email'] || !valMail($f['email']))
{
echo 'Email empty or invalid';
}
else if(strlen($f['pass']) <8 || strlen($f['pass'])>12)
{
echo 'pass must have between 8 and 12 chars!';
}
else
{
$autEmail = $f['email'];
$autpass = $f['pass'];
$query = "SELECT * FROM users where email= '$autEmail'";
$exeqr = mysql_query($query) or die(mysql_error());
$assoc = mysql_fetch_assoc($exeqr);
if(mysql_num_rows($exeqr) == 1 )
{
if($autEmail == $assoc['email'] && $autpass == $assoc['pass'])
{
$_SESSION['assoc'] = $assoc;
header('Location:'.$_SERVER['PHP_SELF']);
}
else
{
echo ' wrong password';
}
}
else
{
echo 'email does no exist';
}
}
}
And the new code I am trying to convert using PDO:
<?php
if(isset($_POST['sendLogin']))
{
$f['email'] = mysql_real_escape_string($_POST['email']);
$f['pass'] = mysql_real_escape_string($_POST['password']);
if(!$f['email'] || !valMail($f['email']))
{
echo 'Email empty or invalid';
}
else if(strlen($f['pass']) <8 || strlen($f['pass'])>12)
{
echo 'pass must have between 8 and 12 chars!';
}
else
{
$autEmail = $f['email'];
$autpass = $f['pass'];
$searchEmail = $pdo->prepare("SELECT * FROM users where email=:email");
$searchEmail->bindValue(":email,$autEmail");
$searchEmail->execute;
$num_rows = $searchEmail->fetchColumn();
$result = $searchEmail->fetch(PDO::FETCH_OBJ);
if($num_rows == 1)
{
if($autEmail == $result['email'] && $autpass == $result['pass'])
{
$_SESSION['result'] = $result;
header('Location:'.$_SERVER['PHP_SELF']);
}
else
{
echo ' wrong password';
}
}
else
{
echo 'email does no exist';
}
}
}
Warning: PDOStatement::bindValue() expects at least 2 parameters, 1 given in $searchEmail->bindValue(":email,$autEmail");
You need to move your ", currently it's including the variable as well as the parameter name resulting in you not passing in the variable to bind to said parameter (which is why you are getting the error telling you you haven't passed in enough arguments).
$searchEmail = $pdo->prepare("SELECT * FROM users where email = :email");
$searchEmail->bindValue(":email", $autEmail);
Notice: Undefined property: PDOStatement::$execute in $searchEmail->execute;
You've forgotten the () brackets from execute(), so PHP is looking for the property of the PDO class called execute instead of the function call.
$searchEmail->execute();
(thanks Prix)
Edit
Your question is now about how to replace this:
$assoc = mysql_fetch_assoc($exeqr);
... with a PDO equivalent. In the manual, there is an example:
$assoc = $searchEmail->fetchAll(PDO::FETCH_COLUMN|PDO::FETCH_GROUP);
Note: fetchAll() is for fetching multiple results. If you're expecting only one result (which you might be, but you aren't limiting your query so it's feasible to return multiple results), you should just use fetch():
$assoc = $searchEmail->fetch(PDO::FETCH_ASSOC);

mysqli deletion

<?php
if (intval($_GET['page']) == 0) {
redirect_to("staff.php");
}
$id = mysqli_prep($_GET['page']);
$query3 = "DELETE FROM page WHERE id = {$id}, LIMIT 1";
$result = mysqli_query($connection, $query3);
if (mysqli_affected_rows($connection) == 1) {
redirect_to("staff.php");
} else {
// Deletion Failed
echo $id ."<br />" . $query3 . "<br />" . $result . "<p>Subject
deletion failed.</p>";
echo "<p>" . mysqli_error() . "</p>";
echo "Return to Main Page";
}
// Keep on working Edit:2#
mysqli_query($connection, "DELETE FROM pages WHERE id = 11 ");
//- Works
Edit 3#
$id = $_GET['page'];
echo "<p>" . $id ."</p>";
$query3 ="DELETE FROM pages WHERE id = {$id} ";
mysqli_query($connection,$query3 );
// Still Works -- YaY for working backwards
// Edit #4 By "now it might be obvious what my error was "pages" not "page"
// Thanks everyone - And thank you for telling me about the error page
// My defense - newbie- Anyway Lesson from this - working backwards
// Takes a while, Error checking Fast!!!!!!
?>
$connection is started and selected. The $id is selected successfully, and the $page = $id, but it still will not work. $query 3 seems fine, but Deletion failed. I don't have any idea what the error is. Thanks for any help in advance.
-Josh Edit Check Error Check
You have a comma after the ID:
$query3 = "DELETE FROM page WHERE id = {$id}, LIMIT 1";
^ remove this
I don't have any idea what the error is.
That's because you didn't check. Every time you prepare or execute a query, you need to check for errors. Most of the functions in mysqli return FALSE if they encounter an error.
$result = mysqli_query($connection, $query3);
if ($result === false) {
trigger_error(mysqli_error($connection), E_USER_ERROR);
header("Location: /error.php");
exit;
}
The failure to check for error cases is one of the most common blunders committed by database programmers.
if ($page == get_page_by_id($id)) {
== for comparison
=== to compare the value and the cast
$val = true;
if ($val === true) {
echo "\$val is bool(true)";
}
if ($val == "true") {
echo "\$val matches value";
}
if ($val === "true") {
// this will never happen
} else {
echo "\$val doesnt === \"true\"";
}
try to use php_flag display_errors on in your .htaccess
this will allow you to see and identify php errors.

mysql_num_rows in an if statement

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";
}

Categories