I'm struggling to retrieve data from a table holding basic information. I've tried to use odbc_fetch functions but I couldn't get them to work. Could someone show me how to retrieve the data from a certain row
<?php
session_start();
?>
<html>
<head>
<title>Profile</title>
</head>
<body>
<?php
$employeeNumber = $_SESSION["user"];
$connect=odbc_connect("CoveringSystem", "", "");
$getData="SELECT FirstName, LastName FROM Details WHERE EmployeeNumber ='$employeeNumber'";
$result = odbc_exec($connect, $getData);
## //I've tried to add the odbc_fetch functions here\\ ##
echo $employeeNumber;
echo $firstName;
echo $lastName;
?>
</body>
</html>
Check this with mysqli :
// First connect to database
$con = mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Than make your query
$getData=mysqli_query($con,"SELECT FirstName, LastName FROM Details WHERE EmployeeNumber ='$employeeNumber'");
//Count row returned
if(mysqli_num_rows($getData)>0){
while($row=mysqli_fetch_assoc($getData)){
$firstName=$row['FirstName'];
$lastName=$row['LastName'];
//then you can do whatever you like with your data
}
}else{
}
Related
Good day,
I have done extensive research on this issue but unfortunately none of the related issues solved my problem.
Here I have a very basic PHP mySQLi db connection. The connection succeeds and so does the query that is run on the table. The issue is that the the result set will not display. All of my references are correct and when I check to see if the result set is populated, it is. I believe the issue is with my while block but no errors are returned when this is run.
Thank you for your time
<?php
$db = mysqli_connect('localhost','root','','securitour') //connection to the database
or die('Error connecting to MySQL server.');
?>
<html>
<head>
</head>
<body>
<?php
$query = "SELECT * FROM location"; //The SQL query
mysqli_query($db, $query) or die('Error querying database.');
$result = mysqli_query($db, $query); //query the table an store the result set in a variable
$row = mysqli_fetch_array($result); //create an array and store the records of the result set in it
if (mysqli_num_rows($result) != 0) //to check if the result set contains data
{
echo "results found"; //THIS is what is returned.
}
else
{
echo "results not found";
}
while ($row = $result->fetch_assoc()) //itterate through the array and display the name column of each record
{
echo $row['name'];
}
mysqli_close($db);
?>
</body>
</html>
Lots of things not right here.
You are processing the mysqli_query() function twice - there is no need.
You are selecting all fields in your SQL query (SELECT *). You should select fields by name.
You're interchanging between procedure and class-based MySQLi - You should stick to one or the other.
Try this instead:
<?php
$db = mysqli_connect('localhost','root','','securitour') //connection to the database
or die('Error connecting to MySQL server.');
?>
<html>
<head>
</head>
<body>
<?php
$query = "SELECT name FROM location"; //The SQL query
$result = mysqli_query($db, $query) or die('Error querying database'); //query the table an store the result set in a variable
if(mysqli_num_rows($result) > 0){
echo "Results found!";
while($row = mysqli_fetch_array($result)){ //create an array and store the records of the result set in it
echo $row['name'];
}
} else {
echo "results not found";
}
mysqli_close($db);
?>
</body>
</html>
You don't need to run mysqli_query() twice. and you need to use mysqli_fetch_assoc for associative array
<?php
$db = mysqli_connect('localhost','root','','securitour') or die('Error connecting to MySQL server.');
?>
<html>
<head>
</head>
<body>
<?php
$query = "SELECT * FROM location"; //The SQL query
$result = mysqli_query($db, $query) or die('Error querying database.'); //query the table an store the result set in a variable
$row = mysqli_fetch_assoc($result); //create an array and store the records of the result set in it
if (mysqli_num_rows($result) != 0) //to check if the result set contains data
{
echo "results found"; //THIS is what is returned.
} else {
echo "results not found";
}
foreach ( $row as $name=>$val) {
echo $name . ':' . $val . '<br>';
}
mysqli_close($db);
?>
</body>
</html>
I am trying to get the result of a database query, which will almost always contain more than one row of data, from an Ajax call in an HTML file, back to the HTML file so that I can display it.
index.html:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<title>My Webpage</title>
<script type="text/javascript">
//Function for getting data from database
function getData() {
$.ajax({
url: "get_data.php",
type: "GET",
success: function(data) {
alert("Finished!");
}
});
}
</script>
</head>
</body>
<!--I'd like to put a table of data here-->
</body>
</html>
get_data.php:
<?php
include "action.php";
$sql_query = "SELECT * FROM " . TABLE;
//Connecting to database
$mysqli = mysqli_connect(SERVER_NAME, USERNAME, PASSWORD, DATABASE);
//Check database connection
if($mysqli === false) {
die ("\nCould not connect: " . mysqli_connect_error());
} else {
echo nl2br("\nConnected successfully! Host info: " . mysqli_get_host_info($mysqli));
}
echo executeQuery($sql_query, $mysqli);
?>
action.php:
<?php
define("SERVER_NAME", "localhost");
define("USERNAME", "root");
define("PASSWORD", "");
define("TABLE", "data_set");
$mysqli = mysqli_connect(SERVER_NAME, USERNAME, PASSWORD);
//Check database connection
if($mysqli === false) {
die ("\nCould not connect: " . mysqli_connect_error());
} else {
echo nl2br("\nConnected successfully! Host info: " . mysqli_get_host_info($mysqli));
}
//Function to execute database queries
function executeQuery($sql_query, $mysqli) {
if(mysqli_query($mysqli, $sql_query)){
echo nl2br("\n\nQuery executed successfully: $sql_query");
} else {
echo nl2br("\n\nERROR: Could not able to execute $sql_query. " . mysqli_error($mysqli));
}
}
?>
I can't seem to figure out how to get the result of the query from action.php to 'get_data.php, back to the original Ajax call fromindex.htmlso that I can build my table. I've tried just usingecho` with the result of the query, but that did not work because there was an error for the conversion of an object to a string.
I don't see any return value from your executeQuery function. The mysqli_query function returns a mysqli_result object, or the boolean false if anything fails. You can use this mysqli_result object to get the data which you require and put it into an array. This array should be encoded into a json response, which is a format which Javascript understands.
So for example:
function executeQuery($sql_query, $mysqli) {
$rows = [];
$result = mysqli_query($mysqli, $sql_query);
if ($result === false) {
// Do something if anything goes wrong here like throwing an exception
}
while ($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
return $rows;
}
Then you can call this function to get the data and convert it to json as follows:
$rows = executeQuery($sql_query, $mysqli);
echo json_encode($rows);
This is the most basic of basic ways, however this exact implementation is not recommended. Outputting the real column names for a table is a vulnerability because everyone can see them, I'd loop through them and change them before using json_encode.
You defined TABLE but where is your DATABASE name? You can't just write down echo in every places. You have to use mysqli_fetch_array function to get the result as array and then send that as json. I just fixed the whole code in one script, guess, it will help.
<?php
define("SERVER_NAME", "localhost");
define("USERNAME", "root");
define("PASSWORD", "");
define("DATABASE", "YOURDATABASE");
define("TABLE", "YOURTABLENAME");
$mysqli = mysqli_connect(SERVER_NAME, USERNAME, PASSWORD);
//Check database connection
if ($mysqli === false) {
die ("\nCould not connect: " . mysqli_connect_error());
}
//Function to execute database queries
function executeQuery($sql_query, $mysqli)
{
$result = mysqli_query($mysqli, $sql_query);
if ($result) {
//You have to run mysqli_fetch_array to get real data as array
return mysqli_fetch_array($result);
}
}
$sql_query = "SELECT * FROM " . TABLE;
//Connecting to database
$mysqli = mysqli_connect(SERVER_NAME, USERNAME, PASSWORD, DATABASE);
//Check database connection
if ($mysqli === false) {
die ("\nCould not connect: " . mysqli_connect_error());
} else {
//echo nl2br("\nConnected successfully! Host info: " . mysqli_get_host_info($mysqli));
}
//after getting the result send output to brower with json encode and then from your ajax response
// You can handle json data easily.
// And for json response you can't just write echo from everywhere in script. Send either die on failure or result on success
$result = executeQuery($sql_query, $mysqli);
header('Content-Type: application/json');
echo json_encode($result, JSON_PRETTY_PRINT);
exit();
I am working on a test login-check with PHP/HTML and MySQL. I got it working great; it successfully connects to the database, it can grab my database values and save them in a variable, etc., but I ran into one slight problem.
I'm using two PHP pages to do the check. The login.php page, which only contains the forum, and the welcome.php page, which does the database connecting. When I ran a test page to just have it echo the database info, it printed out right (testUser, testEmail#email.com, testPassword, 1/1/1900). So when I tried to run my login-authentication check, it just says 'Unknown user!' twice, even when I try the usernames 'usr', 'testUser', and 'testUser2' (I made two tables, and the second one is the same with 2 added to the end). Here's my code.
<html>
<head>
<?php
$title = ucfirst(basename($_SERVER['PHP_SELF'], ".php"));
echo "<title>$title</title>";
?>
</head>
<body>
<form name="form" accept-charset="utf-8" action="welcome.php" method="post">
<span class="header">Username</span><input type="text" name="usr" value="usr"></input><br>
<span class="header">Password</span><input type="text" name="pass" value="pass"></input>
<input type="submit">
</form>
</body>
</html>
<?php
$servername = removed;
$username = removed;
$password = removed;
$dbname = removed;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT ID, USER, PASSWORD FROM usrdatabase";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
// the given info from the form
$usrUser = $_POST["usr"];
$usrPass = $_POST["pass"];
// convert the findings to uppercase to get rid of sensitivity
if (strtoupper($usrUsr) == strtoupper($row["USER"]) && strtoupper($usrPass) == strtoupper($row["PASSWORD"])) {
echo "Welcome $usrUser!<br>Your login was successful! ?>";
}
elseif (strtoupper($usrUsr) == strtoupper($row["USER"]) && strtoupper($usrPass) != strtoupper($row["PASSWORD"])) {
echo "Login failed as $usrUser!";
}
else {
echo "Unknown user!";
}
}
} else {
echo "0 results";
}
$conn->close();
?>
This always produces a 'Unknown user!' Is there something wrong with my check? I want it to go through each user in the database to check the info with each existing user.
Change
strtoupper($usrUsr) == strtoupper($row["USER"])
To
strtoupper($usrUser) == strtoupper($row["USER"])
Fetch single user from the database by using the username since they are unique for each user.
$sql = "SELECT ID, USER, PASSWORD FROM usrdatabase WHERE USER = '" . mysqli_real_escape_string($_POST['usr']) . "' AND PASSWORD = '" . mysqli_real_escape_string($_POST['pass']) . "'";
hey i see your if else contains $usrUsr shoudn't it be $usrUser ? (forgot the e)
I am really new on php and I am trying to create my own php shop cart. After some research I got myself stuck in the "function products" below because seems to me it is not working properly. I expect to see the names of my products on my mysql database but it is not showing anything. My user name is noivaemd_etalhes, I am using my correct password and my database name is noivaemd_cart and I created on this database the table called Products with my list of products available. Can anybody help me to figure out what am I doing wrong on the php instructions below???? I appreciate any help.
<?php
session_start();
$page = 'index.php';
function products() {
$con = mysqli_connect("localhost", "noivaemd_etalhes", "mypassword", "noivaemd_cart") or die (mysqli_error());
$res = mysqli_query($con, "SELECT id, name, description, price FROM Products WHERE quantity > 0 ORDER BY id DESC");
if (mysqli_num_rows($res)==0) {
echo "<font family=verdana><font size=6px><font color= #90882C><font style=normal><font variant= normal><br>No products available<br></font>";
}
else{
while($get_row = mysqli_fetch_assoc($res)) {
echo '<p>'.$res['name'].'</p>';
}
}
}
?>
This code:
while ($get_row = mysqli_fetch_assoc($res)) {
echo '<p>'.$res['name'].'</p>';
}
Should be:
while ($get_row = mysqli_fetch_assoc($res)) {
echo '<p>'.$get_row ['name'].'</p>';
}
As your title ask also tell how to check if the mysqli database connection is successful you can use the below code:
$con = mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
Reference link: http://www.php.net/manual/en/function.mysqli-connect.php
It's not good practice to connect to your database directly in your code. Open another file, and save it has 'dbconnect.php' or whatever you choose to name it. Save it in the same root.
Inside DB connect, you connect to the database like this:
<?php
$mysql_host = "localhost";
$mysql_user = "username";
$mysql_pass = "";
$mysql_dbname = "Products";
$conn_error = "Sorry, Could Not Connect";
if(!#mysql_connect($mysql_host,$mysql_user,$mysql_pass)||!#mysql_select_db($mysql_dbname)){
die($conn_error);
}
?>
In your index.php, inside your php tags, write 'require "dbconnect.php";'.
Then you get your values like this:
$InfoQuery = " SELECT id, product, name FROM table_name WHERE quantity>0 ORDER BY id DESC";
$Info = mysql_query($InfoQuery);
while($InfoRow=mysql_fetch_assoc($Info)){echo "<p>".$InfoRow['id']."<br>". $InfoRow['product']"."<br>". $InfoRow['name']."</p>";}
Edit: What you did wrong is in your while loop, you fetched the table data from $res when it should be fetched from $get_row
I'm trying to retrive my first name and last name for viewprofile.php but i'm getting resource ID#5 . I am CREATING session in Login page after successful authentication. And I am trying to use it here. I'm trying to use a session which has been created to fetch the data from the database.
<html>
<h1> My Profile</h1>
<?php
session_start();
require "config.php";
$con = mysql_connect("localhost", $db_user, $db_pass);
if(!$con)
{
die('cound not connect: '. mysql_error());
}
mysql_select_db($db_name, $con);
# include 'new.php';
echo $_SESSION['username'];
#$usname = $_SESSION['username'];
#echo 'local var: ', $usname;
$sql1 = "SELECT * FROM register WHERE uname='".$_SESSION['username']."'" ;
#echo $sql1 ;
$result= mysql_query($sql1)or die(mysql_error());
#echo "res: " . $result;
while($row = mysql_fetch_array($result))
{
echo $row['fname']." ".$row['lname'];
echo"</br>";
}
mysql_close($con);
?>
</html>
I'm getting resource ID#5. Searched numerous places no luck. Kindly help
Unless I'm mistaken mysql_fetch_array will give you values that can be expressed as $row[0], $row[1] etc whereas mysql_fetch_assoc is what you're trying to use to get $row['fname'] etc
Change your code to
while($row = mysql_fetch_assoc($result))
In either case a print_r($row) within your while loop will you how it's made up.