mysqli fetch array error Couldn't fetch mysqli - php

I am trying to input and display the data on same page through mysqli but it shows an error "Couldn't fetch mysqli on line" and not unable to display the records.
<?php
$db=mysqli_connect("localhost","root","","abc") or die("Not connected".mysqli_error());
$database=mysqli_select_db($db,'abc') or die("Database not found".mysqli_error());
if(isset($_POST['submit'])){
$roll=$_POST['roll'];
$name=$_POST['name'];
$ins=mysqli_query($db,"insert into abc1 (roll,name)values('$roll','$name')");
}
mysqli_close($db);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<form method="post">
Roll No <input type="text" name="roll" />
Name <input type="text" name="name" />
<input type="submit" name="submit" value="Submit" />
</form>
<table><tr>
<td>Roll No.</td>
<td>Name</td>
</tr>
<?php $query=mysqli_query($db,"select * from abc1");
$result=mysqli_query($db,$query);
$id=0;
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC))
{
?>
<tr><td><?php echo $row['roll']; ?></td>
<td><?php echo $row['name']; ?></td>
<?php } ?>
</tr></table>
</body>
</html>
Any help would be appreciated.
Thanks in Advance

You are doing mysqli_query twice.
Try this.
$query = "select * from abc1";
$result = mysqli_query($db, $query);

You are calling mysqli_query function twice:
$query = mysqli_query($db,"select * from abc1");
$result = mysqli_query($db,$query);
Error: Couldn't fetch mysqli on line
Means, you are passing a a resource id in mysqli_fetch_array function instead of Query Statement. so you just need to use this as:
$query = "select * from abc1";
$result = mysqli_query($db,$query);
Side Note:
There is no need to connect db again:
$database=mysqli_select_db($db,'abc')
mysqli_connect() already connected your db.

Related

PHP not returning mysql results

I am brand new to PHP, or database programming in general. For a project I have to query a bookstore database for book info (a very small database) and display it on the following page. Below is the code for my bookstore search page:
<?php
$con = mysqli_connect("localhost", "root", "root") or die("Error connecting to database: ".mysqli_error());
mysqli_select_db($con, "bookstore") or die(mysqli_error());
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Book Store</title>
</head>
<body>
<td><h1>Book Search</h1> </td>
<table width="100%" border="0">
<tr>
<form method="post" action="search.php?go" id="searchform">
<input type="text" name="name">
<input type="submit" name="submit" value="Search By Title">
</form>
<form method="post" action="search.php?go" id="searchform">
<input type="text" name="category">
<input type="submit" name="submit" value="Search By Category">
</form>
</tr>
</table>
</body>
</html>
And the following is a simple search.php code that query's my database and returns results. However I am unable to see any results. The only thing that shows up is "Book Title Search Results" with nothing below. Which obviously means my problem is in my while loop.
<?php
$con = mysqli_connect("localhost", "root", "root") or die("Error connecting to database: ".mysqli_error());
mysqli_select_db($con, "bookstore") or die(mysqli_error());
?>
<!DOCTYPE html>
<html>
<head>
<title>Search Results</title>
<meta http-equic="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<?php
if (isset($_POST['name'])){
$query = $_POST['name'];
$sql = mysqli_query($con, "SELECT * FROM books
WHERE (`title` LIKE '%".$query."%')") or die(mysqli_error($con));
if (mysqli_num_rows($sql) > 0) {
echo "</br> Book Title Search Results </br>";
while ($row = mysqli_fetch_array($sql, MYSQL_ASSOC)) {
echo "</br>Title: " .$row['title']. ", Author: " .$row['author'].", Year: " .$row['year'] . ", Price: $" .$row['price'] ."</br>";
echo '<img src="data:image/jpeg;base64,'.base64_encode( $row['cover'] ).'"/>';
}
}else{ // if there is no matching rows do following
echo "No results";
}
}
?>
</body>
</html>
I have 6 columns in my database: title, author, year, price, category, image (BLOB FILE), and I have checked naming in my query functions but cannot figure anything out. Can anyone push me in the right direction or show me what I'm doing wrong? I'm using MAMP web server.
There is a typo in your code. Use MYSQLI_ASSOC instead of MYSQL_ASSOC. The rest of the code is correct.
try
$con = mysqli_connect("localhost", "root", "root", "bookstore") or die("Error connecting to database: ".mysqli_error());
In your query, remove the braces after the where:
$sql = mysqli_query($con, "SELECT * FROM books WHERE title LIKE '%$query%'") or die(mysqli_error($con));
Then fetch the results with:
while ($row = mysqli_fetch_assoc($sql)) {
//code
}

A form page to submit data to table in database in PHP

I am new to PHP and haven't worked much on it. I am working on a page where I need to save data from a textbox to a table on submit of a button. But somehow nothing seems to be working on press of button click.
Following is my code for the page:
<?php
require_once('auth.php');?>
<?php
if(isset($_POST['formSubmit']))
{
$errorMessage = "";
if(empty($_POST['category'])){
$errorMessage .= "<li>You forgot to enter a Category!</li>";
}
$varCategory = $_POST['category'];
if(empty($errorMessage)) {
require_once('config.php');
$conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE)
or die ('Cannot connect to db');
$result = $conn->query("insert into category (name) values ('".$varCategory."')");
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Member Index</title>
<link href="loginmodule.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h1>Categories</h1><br>
<table>
<tr><td>My Profile | Logout</td></tr>
<tr><td>Welcome <?php echo $_SESSION['SESS_FIRST_NAME'];?></td></tr>
<tr><td><table>
<tr><td>Category</td>
<td>
<form action="member-index.php" method="post">
<input type="text" name="category" maxlength="50" value="<?=$varCategory;?>" />
<input type="submit" name="formSubmit" value="Save" />
</form>
</td>
</tr>
<tr>
<td>
<?php
require_once('config.php');
$conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE)
or die ('Cannot connect to db');
$result = $conn->query("select catid, name from category");
echo "<select name='id'>";
while ($row = $result->fetch_assoc()) {
unset($id, $name);
$id = $row['catid'];
$name = $row['name'];
echo '<option value="'.$id.'">'.$name.'</option>';
}
echo "</select>";
?>
</td>
<td>Delete</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
Change this
if($_POST['formSubmit'] == "Submit") // this condition will never true
to
if($_POST['formSubmit'] == "Save")
OR
if(isset($_POST['formSubmit']))
Also remove die and exit from here
echo "working"; //die; // your insert query will never execute because you placed die here
$result = $conn->query("insert into category (name) values ('".$varCategory."')");
//exit;
if($_POST['formSubmit'] == "Submit")
should be
if(isset($_POST['formSubmit']))
if you have a connection class named auth.php file with function query() then you can use this:
$sql = "insert into category(name) values('".$varCategory."')";
$conn->query($sql);

Undefined index for ID with $_GET

Well, yet another undefined index appears :
I am trying to change a select row in a database, but so far it doesn't seem to work, I only get
Notice: Undefined index: EierID in C:\WampServer\www\Hundeklubben\ChangeO.php on line 19.
I have tried some fixes, but none worked.
<?php require_once('Connections/hundeklubb.php'); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Endring av eier</title>
<link rel="stylesheet" href="index.css" />
</head>
<body>
<?php
if(isset($_GET['EierID'])){ $name = $_GET['EierID']; }
//Tried with both $_GET and $_POST
?>
<?php
$UID = (int)$_GET['EierID'];
$query = mysql_query("SELECT * FROM eiere WHERE EierID = '$UID'") or die(mysql_error());
if(mysql_num_rows($query)>=1){
while($row = mysql_fetch_array($query)) {
$navn = $row['Navn'];
$bosted = $row['Bosted'];
}
?>
<form name="form1" action="update.php" method="POST" id="form1">
<input type="hidden" name="ID" value="<?=$UID;?>">
Navn: <input type="text" name="ud_navn" value="<?=$navn?>"><br>
Bosted: <input type="text" name="ud_bosted" value="<?=$bosted?>"><br>
<input type="Submit" value="Oppdater">
</form>
<?php
}else{
echo 'No entry found. Go back';
}
?>
<?php var_dump($UID); ?>
</body>
</html>
The var_dump gives me int 0. I'm not sure what it is supposed to be.
update.php
<?php require_once('Connections/hundeklubb.php'); ?>
<?php
$ud_ID = (int)$_POST["ID"];
$ud_navn = mysql_real_escape_string($_POST["ud_navn"]);
$ud_bosted = mysql_real_escape_string($_POST["ud_bosted"]);
$query="UPDATE eiere
SET navn = '$ud_navn', bosted = '$ud_bosted'
WHERE ID='$ud_ID'";
mysql_query($query)or die(mysql_error());
if(mysql_affected_rows()>=1){
echo "<p>($ud_ID) Record Updated<p>";
}else{
echo "<p>($ud_ID) Not Updated<p>";
}
?>
It is because $_GET['EierID'] is not set.
Try this :
$UID = isset($_GET['EierID'])?$_GET['EierID']:"";
In update.php also do the same thing : $ud_ID = isset($_POST["ID"])?$_POST["ID"]:"";
If your variable doesn't exist you will get an error trying to cast that int.
<?php
if(isset($_GET['EierID'])){
$name = $_GET['EierID'];
$UID = (int)$_GET['EierID'];
}else{
//set to 0 or any default value you want to set when EierID doesn't exists
$UID = 0;
}
?>

php not passing data to mysql

I have a php page that connects to a mysql database. I know that the connection to the database is good because I have a php code that displays info from the database onto the webpage. When I try to insert new data into the databse, the page refreshes and the data is not inserted. I have checked to insure that the insert into command has the correct values.
<?php
if (isset($_POST['User_Name']))
{
include "connect_to_mysql.php";
$name = mysql_real_escape_string($_POST["Name"]);
$sql = mysql_query("SELECT TestID FROM test WHERE Name='$name' LIMIT 1")or die (mysql_error());
$productMatch = mysql_num_rows($sql);
if ($productMatch > 0)
{
echo 'Sorry you tried to place a duplicate "User Account" into the system, click here';
exit();
}
else
{
$sql = mysql_query("INSERT INTO test (TestID,Name)
VALUES('', '$name')") or die (mysql_error());
$uid = mysql_insert_id();
header("location: index.php");
exit();
}
}
?>
<?php
include "connect_to_mysql.php";
$User_list = "";
$sql = mysql_query("SELECT * FROM test");
$UserCount = mysql_num_rows($sql);
if ($UserCount > 0)
{
while($row = mysql_fetch_array($sql))
{
$id = $row["TestID"];
$name = $row["Name"];
$User_list .= "Users ID: $id - <strong>$name</strong> <br />";
}
}
else
{
$User_list = "You have no users listed in the database.";
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<div align="center" id="mainWrapper">
<div id="pageContent"><br />
<div align="right" style="margin-right:32px;">+ Add New User</div>
<div align="left" style="margin-left:24px;">
<h2>User list</h2>
<?php echo $User_list; ?>
</div>
<hr />
<a name="UserForm" id="UserForm"></a>
<h3>
↓ Add New User Form ↓
</h3>
<form action="index.php" enctype="multipart/form-data" name="myForm" id="myform" method="post">
<table width="90%" border="0" cellspacing="0" cellpadding="6">
<tr>
<td width="20%" align="right">Name</td>
<td width="80%"><label>
<input name="name" type="text" id="name" size="50" />
</label></td>
</tr>
<tr>
<td> </td>
<td><label>
<input type="submit" name="button" id="button" value="Add This Name Now" />
</label></td>
</tr>
</table>
</form>
<br />
<br />
</div>
</div>
</body>
</html>
I see two problems right away (there may be more). First, PHP array keys are case sensitive. You are accessing $_POST['Name'] but your form input is name. Second, you are testing for $_POST['User_Name'] which doesn't appear to exist anywhere:
// Look for name in the $_POST
if (isset($_POST['name']))
{
include "connect_to_mysql.php";
// name is case-sensitive
$name = mysql_real_escape_string($_POST["name"]);
Later, if your table has an AUTO_INCREMENT id on TestID, you should either omit it or insert NULL in the insert statment:
// Don't include TestID if it is AUTO_INCREMENT. That will happen automatically
$sql = mysql_query("INSERT INTO test (Name)
VALUES('$name')") or die (mysql_error());
I think it will work if you change
if (isset($_POST['User_Name']))
to
if (isset($_POST['Name']))
You check the existence of something which doesn't exists in your form.
Addition:
If TestID is autoincrement, change the below
"INSERT INTO test (TestID,Name) VALUES('', '$name')"
to
"INSERT INTO test (Name) VALUES('$name')"
If you do not get any errors that means you have an error in your MySQL syntax two ways to test it would be to copy the syntax into PHPMyAdmin or whatever your native MySQL command line is and see if you get an output error. Or another thing you can do is to modify all your mysql_query(); functions by adding mysql_query()or die(mysql_error());

Form is not being processed, page immediately redirects

I just need a reality check. This page is redirecting to the HTTP_HOST immediately without downloading data or processing the form. It was, at one time working. I broke something but I'm blind to it.
I'm hitting the page with a query that has 1 value pair, like this: http://Nitrofill.biz/tr/Nitrofill_Presentation?num=EV4ghF8p3
Can anybody help me spot the problem?
<?php session_start();
require_once('Connect.php') ;
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>Nitrofill Document</title>
<?php
$sn=$_GET['num'];
echo $sn;
mysql_connect($hostname,$username, $password) OR die('Unable to connect to database! Please try again later.');
mysql_select_db($dbname);
$selectSQL = "select * from `Presentations` where `serialnum` ='" . $sn ."'" ;
$result = mysql_query($selectSQL) or die(mysql_error());
$row = mysql_fetch_array($result, MYSQL_BOTH);
$thedoc = urldecode($row['docurl']);
$therecip=urldecode($row['recipient']);
$thetracker=urldecode($row['tracker']);
$lastacc=urldecode($row['last_accessed']);
?>
</head>
<body>
<form id="notice" action="http://m3sglobal.com/gdform.php" method="post">
<input name="subject" value="<?php echo $therecip . " has viewed the document you sent them.";?> " />
<input type="hidden" name="redirect" value="<?php echo $thedoc ; ?>"/>
<label>Email:</label><input type="text" name="email" value="<?php echo $thetracker ; ?>"/>
<label>Comments:</label><textarea name="comments" cols="40" rows="5">
Document Viewed:<?php echo $thedoc ; ?>
When Accessed:<?php echo $lastacc ; ?>
</textarea>
<input type="submit" name="submit"/>
</form>
</body>
</html>
You're missing .php in the link you have posted. It needs to be
http://nitrofill.biz/tr/Nitrofill_Presentation.php?num=EV4ghF8p3

Categories