trying to call a variable inside a function in php - php

I wanna program a function that shows elements of my data base according to the input I enter
Here is my code but I got an error on the line 34
Notice: Undefined index: table[1]["des_dem"] in
C:\xampp\htdocs\gpc\test.php on line 34
<?php
$element = $_GET["element"];
echo $element;
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "gpc";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// $sql = "SELECT * FROM bons WHERE des_dem='$element'" ;
$sql = "SELECT * FROM bons" ;
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$table = $result->fetch_all(MYSQLI_ASSOC);
} else {
echo "0 results";
}/*
echo $table[1]["des_dem"];
echo "<br>";
echo $table[1]["des_dec"]; */
function afficher()
{
echo $GLOBALS['table[1]["des_dem"]'];
}
echo $table[4]["des_dec"];
echo "<br>";
afficher();
$conn->close(); ?>
<html>
<body>
<br>
<form action="test.php" method="get">
<tr>
<td>Name</td>
<td><input type="text" name="element"></td>
</tr>
<input type="submit" value="Submit">
</form>
</body>
</html>
Thanks a lot for answering my questions :)

You will have to use the global keyword to do this, you cannot call it within the $GLOBALS array like that, do this..
function afficher()
{
global $table;
echo $table[0][1];
}

Related

How to write WHERE referring to a drop down list select?

There is a drop-down list on the PHP website that contains names taken from the database,
after selecting a name from the list, e.g. "Aprilia", I would like all records to be displayed from the database
where mark = Aprilia
I know I should add in the code below just in a SELECT WHERE x = y query
but I just don't know how to do it;
it should look like this in my opinion:
$result = mysqli_query($conn, "SELECT * FROM motorcycles WHERE mark = X");
And I just can't find this X (X should be the user pick from the dropdown list)
How to write it?
Photos:
https://imgur.com/a/PMu4At7
<?php
require_once 'header.php';
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "projectinz";
// Create connection
//$conn = new mysqli($servername, $username, $password, $dbname);
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
<select name="mark" id="mark">
<?php
$query = $conn->query("SELECT mark FROM motocykle");
while($kategoria = mysqli_fetch_array($query))
{
echo '<option>'.$kategoria['mark'].'</option>';
}
?>
</select>
<?php
$wynik = mysqli_query($conn,"SELECT * FROM motocykle");
while($row = mysqli_fetch_array($wynik))
{
echo "<br>".$row['mark']." ".$row['model']." ".$row['capacity']." ".$row['power']."<br>";
}
mysqli_close($conn);
?>
</body>
</html>
EDIT !!!
find1.php
<?php
require_once 'header.php';
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "projectinz";
// Create connection
//$conn = new mysqli($servername, $username, $password, $dbname);
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
<form action="../includes/find.inc.php" method="post">
<select name="mark" id="mark">
<?php
$query = $conn->query("SELECT mark FROM motocykle");
while ($kategoria = mysqli_fetch_array($query)) {
echo '<option value="id">'.$kategoria['mark'].'</option>';
}
?>
</select>
<button type="submit" name="findmoto">Find</button>
</form>
<?php
$wynik = mysqli_query($conn,"SELECT * FROM motocykle ");
while ($row = mysqli_fetch_array($wynik)) {
echo "<br>".$row['mark']." ".$row['model']." ".$row['capacity']." ".$row['power']."<br>";
}
mysqli_close($conn);
?>
</body>
</html>
find.inc.php
<?php
session_start();
if (isset($_POST['findmoto'])) {
require 'dbh.inc.php';
$id = $_POST["id"];
$marka = $_POST["mark"];
echo $id;
echo $marka;
$display = "SELECT * FROM motocykle WHERE id='$id';";
$run = mysqli_query($conn, $display);
if ($run) {
echo $display;
} else {
echo "not";
}
}
BUT:
https://imgur.com/a/RA5wuus
Where is the problem?
<option value="1">Name</option> has attribute value witch is sent to POST when form is submitted. You need to set it with probably ID from table and then after POST you filter by that ID in WHERE part of your SQL.
First change
<select name="mark" id="mark">
<?php
$query = $conn->query("SELECT id, mark FROM motocykle");
while($kategoria = mysqli_fetch_array($query))
{
echo '<option value="'.$kategoria['id'].'">'.$kategoria['mark'].'</option>';
}
?>
</select>
Second change
if(isset($_POST['findmoto'])) {
require 'dbh.inc.php';
$selectedId = intval($_POST["mark"]);
echo $selectedId;
$display = "SELECT * FROM motocykle WHERE id='$selectedId';";
$run = mysqli_query($conn, $display);
if($run)
{
echo $display;
}
else
{
echo "not";
}
}

Pull database info and display to html problem?

I'm trying to display the information from the database to the html page but it is only displaying the message "connected successfully". The name of the database is "admin" and the table within that database is called "users". I have no idea how to get past the message and just display the table I have created.
Index page (index.php):
<?php
include_once('connection.php');
$query="select * from users";
$result=mysql_query($query);
?>
<!DOCTYPE html>
<html>
<title>
<head> Fetch Data Frome Database</head>
</title>
<body>
<table align="center" border="1px" style="width:250px; line-height: 30px;">
<tr>
<th colspan="4"><h2>Account Record</h2></th>
</tr>
<t>
<th>ID</th>
<th>Username</th>
<th>Password</th>
</t>
<?php
while($rows=mysql_fetch_assoc($result))
{
?>
<tr>
<td><?php echo $rows['ID'];?></td>
<td><?php echo $rows['username'];?></td>
<td><?php echo $rows['password'];?></td>
</tr>
<?php
}
?>
</table>
</body>
</html>
CONNECTION PAGE (connection.php):
<?php
//Include your own values for username, password and dbase name
$host = "localhost";
$username = "root";
$password = "root";
$dbname = "admin";
// Create connection
$conn = new mysqli($host, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Try putting all of your PHP into a single block
<?php
include_once('connection.php');
$query="select * from users";
$result=mysql_query($query);
while($rows=mysql_fetch_assoc($result))
{
echo "<tr>";
echo "<td>".$rows['ID']."</td>";
echo "<td>".$rows['username']."</td>";
echo "<td>".$rows['password']."</td>";
echo "</tr>";
}
?>
First problem is that your while loop is not set up correctly. The equals operator will pass the value of mysql_fetch_assoc($result) to $rows so this just wont do anything. Just think that a single equals sign does not mean equal it really means becomes. So rows becomes result. If you have two equals signs you are comparing the two values but this wont help you either. What your really need to do is first set rows to zero then say while the rows are less then the result echo the id echo the username echo the password and add 1 to rows.
So the while loop should look more like this
$rows = 0;
while($rows < mysql_fetch_assoc($result) ){
$rows++
?>
<tr>
<td><?php echo $rows['ID'];?></td>
<td><?php echo $rows['username'];?></td>
<td><?php echo $rows['password'];?></td>
</tr>
<?php
}
}
Assuming that $result=mysql_query($query) actually has a value this should work.
If you need to test if your result is good use PHP's array print to check print_r($result); This will echo all the results to the screen.
So I prefer using this method since its a little better than any other method I have tried. Plus I tuck the connection into a class and it makes it soo much easier to handle db connections.
DB CONNECTION Page:
class Database
{
private $host = "localhost";
private $db_name = "root";
private $username = "root";
private $password = "admin";
public $conn;
public function dbConnection()
{
$this->conn = null;
try
{
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $exception)
{
echo "Connection error: " . $exception->getMessage();
}
return $this->conn;
}
}
Now I create a class for the connection. I usually name it the site name.
require_once "db/config/page/location.php";
class localhost {
// Create conn to db
private $conn;
public function __construct()
{
$database = new Database();
$db = $database->dbConnection();
$this->conn = $db;
}
public function runQuery($sql)
{
$stmt = $this->conn->prepare($sql);
return $stmt;
}
}
Note: when you would like to use the connection on any page.
You can do the following:
EG Index Page:
<?php
include_once('class.php');
$lHost = new localhost();
//calling the users
$stmt = $lHost->runQuery('SELECT * FROM `users`');
$stmt->execute();
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html>
<title>
<head> Fetch Data Frome Database</head>
</title>
<body>
<table align="center" border="1px" style="width:250px; line-height: 30px;">
<tr>
<th colspan="4"><h2>Account Record</h2></th>
</tr>
<t>
<th>ID</th>
<th>Username</th>
<th>Password</th>
</t>
<?php
foreach ($users as $key => $user) {
?>
<tr>
<td><?php echo $user['ID'];?></td>
<td><?php echo $user['username'];?></td>
<td><?php echo $user['password'];?></td>
</tr>
<?php
}
?>
</table>
</body>
</html>
Feel free to ask me any questions.
Try this in your file. Use this file as one first to test.
<html>
<head>
<title>Selecting Table in MySQLi Server</title>
</head>
<body>
<?php
$dbhost = 'localhost:3306';
$dbuser = 'root';
$dbpass = '';
$dbname = 'admin';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname);
if(! $conn ) {
die('Could not connect: ' . mysqli_error());
}
echo 'Connected successfully<br>';
$sql = 'SELECT name FROM tutorials_inf';
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
</body>
</html>
Note: You can test for errors using mysqli_error()such as echo mysqli_error(); after your select query.

Load MySQL Data into Corresponding PHP Variables

I got this work for me, but I'm sure there's a better way to get this done. But, I've searched many hours without finding the exact answer to what I'm looking to do. Basically getting the variable usrID from the URL, I need to search MySQL for the corresponding information to this user. Later I want to use the different fields on my page (better website) to personalize the experience.
<?php
$servername = "localhost";
$username = "authorized-user";
$password = "secret";
$dbname = "agentDB";
$usrID = "001";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM agentInfo WHERE usrID = '$usrID'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$Lname = $row["Lname"];
$Fname = $row["Fname"];
$tl = $row["tl"];
}
}
mysqli_close($conn);
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Load MySQL Data into Corresponding PHP Variables</title>
</head>
<body>
here is the body<br>
My name is: <?php echo $Fname; ?> <?php echo $Lname; ?><?php echo $tl; ?>
</body>
</html>
You could create a variable to store a full name and then "tl" on it like this:
$user_info = $Lname . ", " . $Fname . ": " . $tl;
Then:
<?php echo $user_info; ?>
Wherever you need that information.
If you want to minimize the amount of variables being assigned you could wrap it in a function and return the desired data field:
function fetchUserData(userData) {
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM agentInfo WHERE usrID = '$usrID'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$userData = $row[userData];
}
}
return $userData;
}
mysqli_close($conn);
You can the get the specified data like this:
<?php echo fetchUserData("Fname"); ?>

Notice: Trying to get property of non-object in sign-up.php on line 135

Hi i have a problem qith this select i try to import default items from my dtaabse to a select for a signup of users the error is on this line if ($result->num_rows > 0) can i do!!!?
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "gimnasio";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT idTipo de Documento,Tipo_de_Documento FROM tipo de documento";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>idTipo de Documento</th><th>Tipo_de_Documento</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["idTipo de Documento"]."</td><td>".$row["Tipo_de_Documento"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
<div>
<div class="form-group">
<label>Tipo de Documento:</label>
<select id="tipo_tel" class= "form-control" name="txt_utdoc">
<option value="101">CEDULA DE CIUDADANIA</option>
<?php
while($row = $result->fetch_assoc())
{
?>
<option value="<?php echo $row['idTipo de Documento']; ?>"><?php echo $row['Tipo_de_Documento']; ?></option>
<?php
}
?>
</select>
</div>
</div>
If you are getting a "property of a non-object" error then this suggests that an object you are expecting to be assigned to your variable has not been correctly set.
In your case, $result is either not an object or has returned as null/false.
You should probably use some form of try {} catch($e) {} to make sure that if your database query fails, the error is caught.
Documentation on what will be returned by MySQLi::query() can be found here
http://php.net/manual/en/mysqli.query.php

Dropdown not populating from MySQL

I am trying to populate a dropdown list with PHP from a MySQL database. Right now nothing is populating in my dropdown. I have made sure I have the correct database name, server name, username, and password.
Here is my PHP file queryfunction.php:
<?php
function connect(){
$servername = "localhost";
$username = "root";
$password = "******";
$database = "lab4";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
mysqli_select_db($database);
}
function close(){
mysqli_close();
}
function query(){
$mydata = mysqli_query("Select * from country");
while($record = mysqli_fetch_array($mydata)){
echo '<option value = "' . $record['CountryAbbreviation'] . '">' .$record['CountryAbbreviation'] . '"</option>';
}
}
?>
Here is is my PHP file where I call this:
<?php
include_once "queryfunction.php";
connect();
?>
<!DOCTYPE html/>
<html>
Further down in the doc within a table:
<tr>
<th>Country</th>
<td>
<select name="CountryDropDown">
<?php query() ?>
</select>
<?php close()?>
</td>
</tr>
Try with change this line while($record = mysqli_fetch_array($mydata)){ to this while($record = mysqli_fetch_array($mydata,MYSQLI_ASSOC)){
or show us your $record variable data

Categories