Couldn't fetch mysqli - php

before you send me thousand of links to the problem of other please read my code. i googled my problem for about an hour and tried every suggestion i could find. I got a similar code example from php book but its not working on my local server.
my code:
$mysqli = new mysqli("localhost", "root", "", "poi_site");
if ($mysqli->connect_error){
echo "something went wrong!".mysqli_connect_error();
exit();
}
echo "db connection is stable";
$mysqli->close();
$result = $mysqli->query("SELECT name FROM cities;");
while($row = $result->fetch_array()) {
echo " {$row['name']}";
}
$result->close();
i already tried to get a error output and that showed me that "result" is null, like i expexted the problem from the other people.
my errors at the moment are:
Warning: mysqli::query(): Couldn't fetch mysqli in ...
Fatal error: Call to a member function fetch_array() on a non-object in ...
dont know how to solve the problem. thanks
EDIT: sorry i had a typo in the code here, it was right on my code!

A wrong ";" after cities in here:
$result = $mysqli->query("SELECT name FROM cities;");
$result = $mysqli->query("SELECT name FROM cities");
This has to be $result instead of $ergebnis
while($row = $ergebnis->fetch_array()) {
while($row = $result->fetch_array()) {
U don't need "{" and "}" after and before the $row statement here:
echo " $row['name']";
echo " $row['name']";
Your closing the database, before the query here:
echo "db connection is stable";
$mysqli->close();
Delete this line!

Try to change this code
$result = $mysqli->query("SELECT name FROM cities;");
while($row = $ergebnis->fetch_array()) {
echo " {$row['name']}";
}
with this one and check if also you haven't result
$result = $mysqli_query($conn,"SELECT name FROM cities");
while($row = mysqli_fetch_array($result)) {
echo " {$row['name']}";
}

while($row = $ergebnis->fetch_array()) {
to
while($row = $result->fetch_array()) {
check the very first example here
http://us2.php.net/manual/en/mysqli-result.fetch-array.php
UPDATE :
$mysqli->close();
is done prior to fetch so this should be the last line of your code after u have done with all the operations are done.

Related

Use PHP to generate from an existing database for each row a new specific HTML that i already made

First I'm hitting on a wall here and I really could use your help. I coded the database so I have it all up and working plus all the data inside. I worked the HTML and the CSS media print query and I have it how I want it to look exactly. All I have to do now is:
for every row of the mysql select table I have to fill every specific input form
of the html page I made and print it
Can someone give me a hint of how I can do that?
Assuming you want to connect to your database and simply fetch the id you can do the following.
Ensure you change my_host, my_user, my-password, my_databse,my_tablewith your configuration settings. Then if you want to fetch anything else thanid` just change it to the column name you are looking for.
Be aware we are using PHP here.
// Open Connection
$con = #mysqli_connect('my_host', 'my_user', 'my-password', 'my_databse');
if (!$con) {
echo "Error: " . mysqli_connect_error();
exit();
}
// Some Query
$sql = 'SELECT * FROM my_table';
$query = mysqli_query($con, $sql);
while ($row = mysqli_fetch_array($query))
{
echo $row['id'];
}
// Close connection
mysqli_close ($con);
Check this link to get a in-depth explanation.
You can do this with two pages. One page gives you the overview and the other page gives you a print preview of your invoice.
The overview:
// DB select stuff here
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
echo "<tr>\n";
echo " <td>".htmlspecialchars($row['what'])."</td>\n";
echo " <td>".htmlspecialchars($row['ever'])."</td>\n";
echo " <td>Detail</td>\n";
echo "</tr>\n";
}
The detail page:
$sql = 'SELECT your, columns FROM tab WHERE id = ?';
$stmt = $db->prepare($sql);
$stmt->execute(array($_GET['id']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$row) {
echo "There is no data for the given Id\n";
return;
}
echo "What: ".htmlspecialchars($row['what'])."<br />\n";
echo "Ever: ".htmlspecialchars($row['ever'])."<br />\n";

Populate drop down using PHP ODBC function

Can you help me tracing my problem on populating drop down menu using ODBC Function in PHP. Here's my code:
$conn = $conn = odbc_connect("mm370lib", "ictapps", "s3cur3344");
if(! $conn){
print( "Cannot connect to database" );
exit;
}
$qry1 = "SELECT * FROM APSUPP";
//$res = odbc_do($conn, $qry);
$res1 = odbc_exec($conn, $qry1);
echo "<select class='form-control' name='vendor_name'>";
while($row1 = odbc_fetch_row($res1)){
echo "<option value='".$row1["ASNUM"]."'>".$row1["ASNAME"]."</option>";
}
odbc_free_result($res1);
echo "</select>";
It is not showing the fetch data from database.
See attached file
According to the doc, odbc_fetch_row() does not return a row, but just true or false, indicating if a row was fetched. See here for more information: http://php.net/manual/en/function.odbc-fetch-row.php
So, following the doc, you need to call odbc_result() after you've fetched a row. See here for more info: http://php.net/manual/en/function.odbc-result.php
It should probably be something like this (I do not have a php environment here right now, so this code is untested):
while(odbc_fetch_row($res1))
{
$asnum = odbc_result($res1, "ASNUM");
$asname = odbc_result($res1, "ASNAME");
echo "<option value='".$asnum."'>".$asname."</option>";
}

Printing mysqli query results

i am trying to print the results of a php query my php code is:
<?php
include 'header.php';
include 'conect.php';
$resultlog = mysqli_query("SELECT * from cpi ,$con);
while($row = mysql_fetch_array($resultlog))
print $row;
mysqli_close($con);
?>
but it result an error
Parse error: syntax error, unexpected end of file
Firstly, the DB connection comes first in mysqli plus, there's a missing quote.
You're also mixing APIs.
Then add the proper bracing.
$resultlog = mysqli_query($con,"SELECT * from cpi") or die(mysqli_error($con));
while($row = mysqli_fetch_array($resultlog)){
print $row;
}
mysqli_close($con);
Make sure your DB connection which is not shown, is in fact mysqli and not mysql, nor PDO.
None of those APIs intermix.
However, just doing a print $row may probably not show you what you like to get.
Therefore, you may need to elaborate on that.
You're probably wanting to do something like:
echo $row['your_column_name'].'<br />';
or as Ghost stated:
print $row[0]; or print $row['column_name']
"Its working fine. But can we print all result through one command?"
Yes, like this:
$resultlog = mysqli_query($con,"SELECT * from cpi") or die(mysqli_error($con));
$row = mysqli_fetch_array($resultlog);
foreach($row as $r) {
echo $r . "<br>";
}
try this:
<?php
include 'header.php';
include 'conect.php';
$resultArray = array();
$resultlog = mysqli_query($con, "SELECT * from cpi");
while($row = mysqli_fetch_array($resultlog)){
$resultArray[] = $row;
}
mysqli_close($con);
print_r($resultArray);
?>

Why isn't this query returning an object?

I am learning PHP and MySQL from 'PHP and MySQL web dev'. Currently I am finding difficulties in displaying results from database. Here is the code:
<body>
<?php
$searchtype = $_POST['searchtype'];
$seachterm = trim($_POST['searchterm']);
if(!$searchtype || !$seachterm){
echo "You did not enter all the details. Bye";
exit;
}
if(!get_magic_quotes_gpc()){
$searchtype = addslashes($searchtype);
$seachterm = addslashes($seachterm);
}
# $db = new mysqli('localhost', 'bookorama', 'bookorama123', 'books');
if(mysqli_connect_errno()){
echo "Sorry Could not connect to db";
exit;
}
$query = "select * from books where".$searchtype."like '%".$seachterm."%'";
$result = $db -> query($query);
$num_of_results = $result->num_rows; // Line 47
echo "Num of books found is ".$num_of_results." ";
for($i = 0; $i < $num_of_results; $i++){
$row = $result -> fetch_assoc();
echo "<p><strong>".($i+1).". Title: ";
echo htmlspecialchars(stripslashes($row['title']));
echo "</strong><br />Author: ";
echo stripslashes($row['author']);
echo "<br />ISBN: ";
echo stripslashes($row['isbn']);
echo "<br />Price: ";
echo stripslashes($row['price']);
echo "</p>";
}
$result->free();
$db -> close();
?>
</body>
When I run the above code, this is the error i get.
Notice: Trying to get property of non-object in /opt/lampp/htdocs/xampp/php/php_crash/phptomysql/connect.php on line 47
Num of books found is
Fatal error: Call to a member function free() on a non-object in /opt/lampp/htdocs/xampp/php/php_crash/phptomysql/connect.php on line 64
What am I doing wrong?
There's probably an error in your SQL query and $result is false instead of the result object.
I think it's probably because you're missing some spaces in the query. This line:
$query = "select * from books where".$searchtype."like '%".$seachterm."%'";
should be something like:
$query = "SELECT * FROM books WHERE '" .$searchtype. "' LIKE '%".$seachterm."%'";
It would help if we knew the values of:
$_POST['searchtype'];
$_POST['searchterm'];
You're not checking to make sure that $result is what you think it is. It's very likely that something went wrong with your query, and the return value of $db->query() is false. It's a good idea to check for that to make sure your query actually worked.
Try using this code:
$result = $db->query($query);
if ($result === false) {
// Query failed - we can't continue
die('My query failed, I want to be a teapot instead.');
}
// Now it's safe to operate on $result, deal with a successful query, but no results
if ($result->num_rows == 0) {
echo 'no results found.';
// display any other output, search again?
exit;
}
// At this point you have results to display
Now, as to why your query is failing, take a look at this part closely:
"select * from books where".$searchtype."like '%"
You need some spaces. If $searchtype was 'foo', your query would actually expand to:
select * from books wherefoolike
Try instead:
"select * from books where ".$searchtype." like '%"
Notice the space after 'where' and before 'like'? That should probably fix it.
I'm not going to harp too much about making sure your query is properly prepared for safety, your book should go into that - but do keep it in mind.

Error message in PHP when there's no data via MYSQL?

I've got a php file fetching some data from a MYSQL database. This is my code so far:
<?php
include 'DB.php';
$connection=mysql_connect(DB_SERVER,DB_USER,PASS);
$db=mysql_select_db(DB_Name);
$sql="select * from lookup where id = ".$_GET['id'];
$res=mysql_query($sql) or die(mysql_error());
while($row=mysql_fetch_array($res))
{
echo $row['message'];
}
?>
What would I have to add so that if there was no data, there'd be an error message? I'm guessing an If/else statement but I'm not sure how to fit it in with the while syntax.. any help?
$res = mysql_query(...) ...;
if (mysql_num_rows($res) == 0) {
die("Hey, nothing here!");
}
Beyond that:
a) you're utterly vulnerable to SQL injection attacks. Stop your coding project and learn about them before you go any further.
b) stop using the mysql_*() functions. They're deprecated.
You can use $count = mysql_num_rows($res); to get the number of rows returend. Then you can use an if statement to display whatever error.
I did it like mentioned above:
$query = "select * from lookup where id = ".$_GET['id'];
$result = mysql_query($query) or die ("Error in query: $query " . mysql_error());
$num_results = mysql_num_rows($result);
if ($num_results == 0){
echo "nothing here</br>";
}
else{
echo "<b> $num_results </b> result(s) match your query</br>";
while($row=mysql_fetch_array($res))
{
echo $row['message'];
}
You can of course leave the "echo $num_results..." out, but there you can give the number of results, which is sometimes quite useful.

Categories