Undefined offset trying to echo data from database [duplicate] - php

This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 5 years ago.
I am trying to echo out the number of agility that is set in the database. This is my current code, if you could check it out and see if there is anything i need to change to get it working. Currently im getting the error
Notice: Undefined offset: 0 in
$dbserver = "localhost";
$dbusername = "root";
$dbpassword = "*******";
$db = "********";
//CREATE CONNECTION
$conn = new mysqli($dbserver, $dbusername, $dbpassword, $db);
$id = $_SESSION['loggedin'];
$query = "SELECT * FROM stats WHERE id='$id'";
$stmt = mysqli_query($conn, $query);
$result = mysqli_fetch_all($stmt,MYSQLI_ASSOC);
<div class="Agility">
<h2>Agility</h2>
<p><?php echo $result[0]['agility']; ?></p>
</div>

First off, since your id field is probably unique, you should limit the query to one. Then, check the number of rows returned by the query before displaying the results in case there are none.
$query = "SELECT * FROM stats WHERE id='$id' LIMIT 1";
$stmt = mysqli_query($conn, $query);
if(mysqli_num_rows($stmt) > 0){
$result = mysqli_fetch_all($stmt,MYSQLI_ASSOC);
?>
<div class="Agility">
<h2>Agility</h2>
<p><?php echo $result[0]['agility']; ?></p>
</div>
<?php } else { ?>
<p>There are no results.</p>
<?php } ?>

Related

how to fix undefined variable issue in code while extracting data from database in input field [duplicate]

This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 3 years ago.
I am trying to fetch the data from database for a an input field product code and i need to use its value to update the rest of the column values in the database but instead it is creating a different record and in the value field of the input box 'named' code, it shows and undefined variable error, please help.
HTML code:
<div class="small-8 columns">
<input type="text" id="right-label" placeholder="Product_code"
value="<?php echo "$pcode"?>" name="code">
</div>
PHP Script:
<?php
$servername="localhost";
$username="root";
$password="";
$dbname="bolt";
try{
$conn = new
PDO("mysql:host=$servername;dbname=$dbname",$username,$password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_POST["submit"])){
$pcode = ($_POST["code"]);
$pname = ($_POST["Pname"]);
$pdesc = ($_POST["desc"]);
$pimg = $_FILES["Img_name"]["temp_name"];
$imgExt = strtolower(pathinfo($pimg,PATHINFO_EXTENSION));
$valid_extensions = array('jpeg','jpg','png','gif','pdf');
$pqty = ($_POST["Pqty"]);
$pprice = ($_POST["Pprice"]);
$sql="UPDATE products SET product_name=$pname,product_desc=$pdesc,
product_img_name=$pimg,qty=$pqty,price
=$pprice) WHERE product_code=$pcode";
$stmt = $conn->exec($sql);
$stmt->execute();
echo $stmt->rowCount() . "new records added succesfully";
}
}
catch(PDOException $e){
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
$sql is declared within the if condition, if if(isset($_POST["submit"])){
is false, you will get this error because $sql is not within the scope. Declare it on above condition and initialize it.

What did I do wrong in my Database Query with PHP [duplicate]

This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 5 years ago.
I have a database and a table in it which is looking like this
ID Picture Description.
In my PHP-Code I try to get the "Picture" which is just a text right now and the Description. But I always get
Undefined Index: Description
Undefined Index: Picture
Here my Code:
<?php include ("db.php");
$conn = new mysqli($servername, $username, $password, $db);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Picture, Description FROM family WHERE ID = 1 ";
$result = $conn->query($sql)
or die ("MySQL-Error: " . $conn->error);
if ($result->num_rows >0) {
while ($row = mysqli_fetch_row($result)){
echo "Pic: " . $row["Picture"]. " - Description: " . $row["Description"]. "
}
}
else {
echo "Not good";
}
$conn->close();
echo "Connected successfully"; ?>
What does the error mean
EDIT: I solved it changed mysqli_fetch_row to mysqli_fetch_assoc
mysqli_fetch_row returns an enumerated array starting at 0, not an associative array. See: http://php.net/manual/en/mysqli-result.fetch-row.php
Here's the issue:
while ($row = mysqli_fetch_row($result))
you should use mysqli_fetch_array() or mysqli_fetch_assoc()

Notice: Undefined index: id [duplicate]

This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 7 years ago.
I have used a prepared statement to define the id index however, it is telling me that it is undefined for some reason, where and what do i change for this to work?
<?php
$db_username='student';
$db_password='student';
$db = new PDO ('mysql:host=192.168.56.2;dbname=Assessment', $db_username, $db_password);
$result = $db ->prepare("SELECT * FROM Jobs WHERE jobname='".$_GET['id']."' ");
$result->execute();
Try this:
<?php
$db_username='student';
$db_password='student';
$db = new PDO ('mysql:host=192.168.56.2;dbname=Assessment', $db_username, $db_password);
if(isset($_GET['id'])) {
$result = $db ->prepare("SELECT * FROM Jobs WHERE jobname=?");
$result->execute(array($_GET['id']);`enter code here
}
else {echo('$_GET["id"] not set');}
First, verify that $_GET['id'] has a value. Second, for security, change some lines:
$result = $db ->prepare("SELECT * FROM Jobs WHERE jobname=:id");
$result->execute(array(':id' => $_GET['id']));

Get values from mysql table into dropdown menu (undefined variable) [duplicate]

This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 7 years ago.
this is probably a very simple question to solve, however I've been stuck with this for a while and I can't figure out for the life of me what's wrong with my code. It may be just a syntax mistake but I've gathered this code from other questions and it should work but I keep getting the errors : - Undefined variable : mysqli and - Call to a member function query() of a non-object , both in the line "$result = $mysqli->query($sql);".
Here's the snippet of my code where I have the dropdown menu set up.
<label class="control-label" for="formInput85">Professor</label>
<?php
$sql = "SELECT name FROM professores";
$result = $mysqli->query($sql);
echo "<select class=".'"form-control"'.">";
while ($row = $result->fetch_assoc()) {
echo "<option value='" . $row['name'] . "'>" . $row['name'] . "</option>";
}
echo "</select>";
?>
And here's my code in the very beginning of the page, that is connecting to my database in phpmyadmin.
<?php
session_start();
echo $_SESSION['name'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "teste";
$conn = new mysqli($servername,$username,$password,$dbname);
?>
Thank you for your help! If you have any tips on how to send the value selected into another row of the table I gladly appreciate it as it will be my next step :)
$mysqli is not the right variable in this case. So this line:
$result = $mysqli->query($sql);
has to become
$result = $conn->query($sql);

getting notice like undefined index [duplicate]

This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 8 years ago.
$result = mysql_query("SELECT * FROM customers
WHERE loginid='$_POST[login]' AND accpassword='$_POST[password]'");
if(mysql_num_rows($result) == 1)
{
while($recarr = mysql_fetch_array($result))
{
$_SESSION[customerid] = $recarr[customerid];
$_SESSION[ifsccode] = $recarr[ifsccode];
$_SESSION[customername] = $recarr[firstname]. " ". $recarr[lastname];
$_SESSION[loginid] = $recarr[loginid];
$_SESSION[accstatus] = $recarr[accstatus];
$_SESSION[accopendate] = $recarr[accopendate];
$_SESSION[lastlogin] = $recarr[lastlogin];
}
$_SESSION["loginid"] =$_POST["login"];
header("Location: accountalerts.php");
}
else
{
$logininfo = "Invalid Username or password entered";
}
Notice: Undefined index:login and
Notice: Undefined index:password
try to help me out
getting error message in second line
It seems as if u did not pass the POST params used inside your query:
> $result = mysql_query("SELECT * FROM customers
> WHERE loginid='$_POST[login]' AND accpassword='$_POST[password]'");
You have to send key value pairs explicitly to your script. One for login and one for password.
You need to wrap the index names in quotes, and your query string is hella messy.
$query = sprintf(
"SELECT * FROM customers WHERE loginid='%s' AND accpassword='%s'",
$_POST['login'],
$_POST['password']);
$result = mysql_query($query);
That whole thing should be wrapped in a block like:
if( isset($_POST['login']) && isset($_POST['password']) ) {
//code here
} else {
echo "No username/password supplied.";
}
mysql_* functions are going away, learn to use mySQLi or PDO.
Your query is as wide-open to SQL injection as anything could ever possibly be. Look into parameterized queries with mySQLi or PDO, or at least validating your data before including it in your query.
Here's a PDO example:
//create DB object
$dbh = new PDO('mysql:host=mysql.domain.com;dbname=mydb', $username, $password);
//write query
$query = "SELECT * FROM customers WHERE loginid = ? AND accpassword = ?";
//define parameters to replace ?
$params = array($_POST['login'], $_POST['password']);
//prepare the statement
$sth = $dbh->prepare($query);
//execute
if( ! $sth->execute($params) ) {
//error reporting
die('Query failed: ' var_export($dbh->errorInfo(), true));
}
//fetch all results as associative array
$results = $dbh->fetchAll(PDO::FETCH_ASSOC)l
//display
var_dump($results);

Categories