Cannot Display Data from MySQL table - php

I've got a pretty standard call to a MySQL database and for some reason I can't get the code to work. Here's what I have:
$mysqli = mysqli_connect("localhost","username","password");
if (!$mysqli)
{
die('Could not connect: ' . mysqli_error($mysqli));
}
session_start();
$sql = "SELECT * FROM jobs ORDER BY id DESC";
$result = $mysqli->query($sql);
$num_rows = mysqli_num_rows($result);
Now, first, I know that it is connecting properly because I'm not getting the die method plus I added an else conditional in there previously and it checked out. Then the page displays but I get the errors:
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in blablabla/index.php on line 11
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in blablabla/index.php on line 12
I've double-checked my database and there is a table called jobs with a row of "id" (it's the primary row). The thing that confuses me is this is code that I literally copied and pasted from another site I built and for some reason the code doesn't work on this one (I obviously copy and pasted it and then just changed the table name and rows accordingly).
I saw the error and tried:
$num_rows = $mysqli_result->num_rows;
$row_array = $mysqli_result->fetch_array;
and that fixed the errors but resulted in no data being passed (because obviously $mysqli_result has no value). I don't know why the error is calling for that (is it a difference in version of MySQL or PHP from the other site)?
Can someone help me track down the problem? Thanks so much. Sorry if it's something super simple that I'm overlooking, I've been at it for a while.

You didn't selected the database
$mysqli = mysqli_connect("localhost","username","password","database");

The problem is you haven't selected the database.
use this code for select database.
$mysqli = mysqli_connect("localhost","username","password");
mysqli_select_db("db_name",$mysqli);
You have to select database in order to fire mysql queries otherwise it will give you error.

I believe that schtever is correct, I do not think you are selecting the database. It isn't in the code snip and if you search online you see other people with similar errors and it was because the database wasn't selected. Please let us know if you selected a database before anything else is checked. Thanks.

Try this:
session_start();
$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
if ($mysqli->connect_errno)
{
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
$mysqli->close();
}
$query ="SELECT * FROM jobs ORDER BY id DESC";
$values = $mysqli->query($query);
if($values->num_rows != 0)
{
while($row = $values->fetch_assoc())
{
//your results echo here
}
}
else
{
//if no results say so here
}

See this manual for mysqli_connect you can select the database right in this function.

Related

Simple MySQL call to select an integer at a specific key not working?

I have this PHP:
<?php
$client_ip = $_SERVER['REMOTE_ADDR'];
$connection = new mysqli("localhost", "MyNotSoSecretUsername", "MySuperSecretPassword", "MyNotSoSecretDatabaseName");
if ($connection->connect_error) {
die("Connection failed: " . $Connection->connect_error);
}
$check_emails_sent_query = "SELECT `emails` FROM `email-ips` WHERE `ip`='11.111.111.111'";
$check_emails_sent_result = $connection->query($check_emails_sent_query);
echo $check_emails_sent_result;
?>
This is a small piece of a much larger function on my site. This snippet is simply intended to get the value of the "emails" column (Which is an int column if that makes a difference) of my table where the IP matches the client's IP.
I added a fake entry for 11.111.111.111 in my database, and used the exact same query on PHPmyAdmin's SQL console. I got a result on the PHPmyAdmin console, but nothing is echoed here.
I have also checked that the connection is good, as you can see in my code. Additionally, I pasted another query from another part of my function, which retrieved its data just fine.
AS stupid or obvious as it may be, I can't seem to figure out why this particular query out of almost twenty won't retrieve its data?
Mysqli query() returns and object. Using the object:
<?php
$client_ip = $_SERVER['REMOTE_ADDR'];
$connection = new mysqli("localhost", "MyNotSoSecretUsername", "MySuperSecretPassword", "MyNotSoSecretDatabaseName");
if ($connection->connect_error)
{
die("Connection failed: " . $Connection->connect_error);
}
$check_emails_sent_query = "SELECT `emails` FROM `email-ips` WHERE `ip`='11.111.111.111'";
if ($check_emails_sent_result = $connection->query($check_emails_sent_query))
{
while($obj = $check_emails_sent_result->fetch_object())
{
$echo $obj->emails;
}
}
?>
You could use fetch_row() instead of fetch_object().
Documentation for the object is here:
http://php.net/manual/en/class.mysqli-result.php
mysqli_query()
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.
You can get your email by using
if ($result = $connection->query($check_emails_sent_query)) {
while ($row = $result->fetch_row()) {
printf ("%s (%s)\n", $row[0]);
}
}

mysqli_error() expects parameter 1 to be mysqli, null given

I have a a form that pulls data from a database(mysql to be specific) and echos the data into the value section of <input> tags. It doesn't seem to be working I have coded a view section of my website to do the same thing but from a different table in my database. I use the same code to make making changes easy and if another developer works on my site in the future. Anyway it doesn't seem to be working I'm not sure why though.
The full error I get:
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in /home/caseol5/public_html/jj/admin/news_update.php on line 9
Here is line 9 that the error is referring to:
$result = mysqli_query($link,$sql);
I know that both of those function are not null as I did:
echo $link
echo $sql
before that line after I started feting the error and they both are not null.
Here is the full code segment:
$nid = $_GET['nid'];
include ("../sql/dbConnect.php");
$sql = "SELECT * FROM jj_news WHERE news_id = $nid";
echo "<p>The SQL Command: $sql </p>";
echo "<p>Link: $link </p>";
$result = mysqli_query($link,$sql);
if (!$result)
{
echo "<h1>You have encountered a problem with the update.</h1>";
die( "<h2>" . mysqli_error($link) . "</h2>") ;
}
$row = mysqli_fetch_array($result);
$ntitle = $row['news_title'];
$ntline = $row['news_titleline'];
$ndesc = $row['news_desc'];
$nother = $row['news_other'];
I have looked into mysqli_query and I can't find anything I'm missing. I have also tired breaking the code down (and running parts of it and it gives the same error. My guess is it something small that I missed. I've looked at other question on this site that do that are a little similar but none seem to help. I've been looking at this for a while now and need another pair of eyes.
Update
As requested the contents of my dbconnect.php file:
$hostname = "localhost";
$username = "caseol5_jjoes";
$database = "caseol5_jj_site";
$password = "password1";
$link = mysqli_connect($hostname, $username, $password, $database);
$link = mysqli_connect($hostname,$username,$password,$database) or die("Error " . mysqli_error($link));
if (!$link)
{
echo "We have a problem!";
}
As clearly stated in the error message, mysqli_querydocs expects the first parameter to be a mysqli resource. In your case, this parameter is called $link but it holds a null value. A proper mysqli resource is normally obtained from connecting with the database by making use of mysqli_connectdocs
I expect the ../sql/dbConnect.php file holds the logic to connect with the database. Verify whether the $link variable is indeed initialized there. If it's not there, try to find an occurrence of mysqli_connect - maybe the resource is set to a different variable.
Without knowing what exactly is in ../sql/dbConnect.php, your problem right now is that you do not have a valid mysqli resource to use for mysqli_query.

Warning: mysqli_query(): Couldn't fetch mysqli in C:\ ... on line 13

although this question has been asked (and answered) many times, I didn't find a solution to the problem.
Here is my code:
<?php
#session_start();
include("./include/config.php");
include("./include/db_connect.php");
include("functions.php");
if (!isset($_GET['artikelID'])){$_GET['artikelID'] = "";}
if (!isset($_SESSION['UserID'])){$_SESSION['UserID'] = "";}
$sql = "SELECT kundenID FROM kunden WHERE username = '".$_POST['myusername']."' AND password = '".md5($_POST['mypassword'])."' ";
$result = mysqli_query($connect, $sql) OR die("<pre>\n".$sql."</pre>\n".mysqli_connect_error()); // this is line 13
$row = mysqli_fetch_assoc($result);
if (mysqli_num_rows($result)==1){
doLogin($row['kundenID'], isset($_POST['Autologin']));
header("location:cart.php?action=add&artikelID=".$_GET['artikelID']."&id=". $_SESSION['UserID'] ." ");
}
else {
header("location:k_login.php?error=TRUE ");
}
include("./include/db_close.php");
?>
mysqli_connect_error() shows me the absolute correct sql-query; the sql-query is tested with a tool named mysql-front and brings exactly one (and the correct one) result, which is 'kundenID'.
I have tested many things (like $_SESSION['connect'] or $_GLOBALS['connect'] instead of $connect in db_connect.db), but with no result.
Can anyone please help me?
-- Update --
Why does nobody answer?
Is the description of the problem unclear?
The db-connection is established like this:
<?php
error_reporting(E_ALL);
$connect = mysqli_connect($dbserver,$dbuser,$dbpass,$dbname);
// Check connection
if (mysqli_connect_errno()){
echo "Zeile ".__LINE__.": Datenbankverbindung ist fehlgeschlagen ! " . mysqli_connect_error();
exit();
}
?>
All the db-variables are known in the checklogin-script (tested). All the $_POST-variables are also known in the checklogin-script (tested). I even tried a hard-coded sql-query (with the real data of the test-record in the db).
The result is still the same: mysqli_connect_error() reports the correct query - but then nothing more happens.
I have spent more than 10 hours in the meantime. I really would appreciate, if someone could help me.
Couldn't fetch mysqli means that PHP is unable to identify the contents of your $connect variable as a valid mysqli connection. Try adding some error handling into "./include/db_connect.php" to get an idea of what happened to the mysqli connection that is preventing you from using it.

Outputting contents of database mysqli

Hi I know this is a little general but its something I cant seem to work out by reading online.
Im trying to connnect to a database using php / mysqli using a wamp server and a database which is local host on php admin.
No matter what I try i keep getting the error Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given when i try to output the contents of the database.
the code im using is:
if (isset($_POST["submit"]))
{
$con = mysqli_connect("localhost");
if ($con == true)
{
echo "Database connection established";
}
else
{
die("Unable to connect to database");
}
$result = mysqli_query($con,"SELECT *");
while($row = mysqli_fetch_array($result))
{
echo $row['login'];
}
}
I will be good if you have a look at the standard mysqli_connect here
I will dont seem to see where you have selected any data base before attempting to dump it contents.
<?php
//set up basic connection :
$con = mysqli_connect("host","user","passw","db") or die("Error " . mysqli_error($con));
?>
Following this basic standard will also help you know where prob is.
you have to select from table . or mysqli dont know what table are you selecting from.
change this
$result = mysqli_query($con,"SELECT *");
to
$result = mysqli_query($con,"SELECT * FROM table_name ");
table_name is the name of your table
and your connection is tottally wrong.
use this
$con = mysqli_connect("hostname","username","password","database_name");
you have to learn here how to connect and use mysqli

Need HELP in converting MySQL to MySQLI in my PHP script? [duplicate]

This question already has answers here:
How to change mysql to mysqli?
(12 answers)
Closed 1 year ago.
I need some help in converting my script from using mysql to mysqli I have been trying for ever to do this and keep getting errors I have read articles on how to do this and still can get it to work.
Here is the original working script below.
<?php
require_once ('./mysqli_connect.php'); // Connect to the db.
if (isset($_POST['submitted'])) {
if ($dbc = mysql_connect (DB_HOST, DB_USER, DB_PASSWORD)) { // Make the connnection.
if (!mysql_select_db (DB_NAME)) { // If it can't select the database.
// Handle the error.
trigger_error("Could not select the database!\n<br />MySQL Error: " . mysql_error());
exit();
} // End of mysql_select_db IF.
} else { // If it couldn't connect to MySQL.
// Print a message to the user, include the footer, and kill the script.
trigger_error("Could not connect to MySQL!\n<br />MySQL Error: " . mysql_error());
exit();
} // End of $dbc IF.
// grab the tag
$tag = mysql_real_escape_string($_POST['tag']);
// see if the tag already exists and potentially what the current count is
$query = "SELECT id, count, page FROM tags WHERE tag='$tag'";
$result = mysql_query($query);
//--if there is a row, that means the tag exists
if(mysql_num_rows($result))
{
//--pull out the tag ID and the current count and increment by one.
$tag_info = mysql_fetch_array($result);
$tag_info_id = $tag_info["id"];
$tag_info_count = $tag_info["count"] + 1;
//--update the table with the new count
$sql_update_cnt = "UPDATE tags SET count='$tag_info_count'
WHERE id='$tag_info_id'";
mysql_query($sql_update_cnt);
echo "$tag now with $tag_info_count instances";
}
else
{
// tag is not there, so insert a new instance
$query = "INSERT INTO tags (tag, count) VALUES ('$tag', 1)";
if (!mysql_query($query, $dbc))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
}
mysql_close($dbc);
}
?>
Here is the errors I keep getting.
Warning: mysqli_select_db() expects exactly 2 parameters, 1 given on line 13
Warning: mysqli_error() expects exactly 1 parameter, 0 given on line 16
If you're going to go through the hassle, I would really recommend you consider PDO instead.
It's all a matter of changing mysql to mysqli.
For example, you could call mysqli_query just like you do mysql_query here.
When you call these functions, you need to pass in the database reference as the first parameter.
See the mysqli function reference here
It's been a while since I've done a mysql->mysqli conversion (like 2 or 3 years), but IIRC there are some functions for which you also have to reverse the parameter order. Isn't that lovely?

Categories