Cannot query MySQL database via PHP - php

In my PHP code, i'm easily writing records to my database but for some reason i can't read anythign out. My PHP code is:
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM companies";
if ($conn->query($sql) === TRUE)
{
echo "query success";
while($row = $result->fetch_assoc())
{
echo "ID: " . $row["ID"]. " - Name: " . $row["name"]. "<br>";
}
}
else
{
echo "query failure";
echo "Error: " . $sql . "<br>" . $conn->error;
}
$sql = "INSERT INTO companies (name)
VALUES ('mycompany')";
if ($conn->query($sql) === TRUE)
{
echo "insert success";
}
else
{
echo "insert failure";
echo "Error: " . $sql . "<br>" . $conn->error;
}
The output I get from the browser when i run it is:
query failureError: SELECT * FROM companies
insert success
I've tried variations of apostrophes, carets, quotes in that $sql string. I've tried running this query in HeidiSQL and it works fine. Any ideas where I'm going wrong? Any suggestions of more basic stuff I can try to narrow down the source of the problem?
thanks!

Using mysqli->query() with a SELECT statement returns an instance of mysqli_result. It is not identical to true (=== true), but nor does it represent an error.
Moreover, $result is undefined.
Use this instead:
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM companies";
if (($result = $conn->query($sql)) !== FALSE)
{
echo "query success";
while($row = $result->fetch_assoc())
{
echo "ID: " . $row["ID"]. " - Name: " . $row["name"]. "<br>";
}
}
else
{
echo "query failure";
echo "Error: " . $sql . "<br>" . $conn->error;
}
...
This simply changes your === TRUE check to !== FALSE. MySQLi::query() returns boolean FALSE on failure, boolean TRUE on a successful query without result sets or a mysqli_result upon success with a result set.
This also assigns the result of query() into $result.

You have not assign the query result to $result variable.
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM companies";
$result = $conn->query($sql);
if ($result === TRUE)
{
echo "query success";
while($row = $result->fetch_assoc())
{
echo "ID: " . $row["ID"]. " - Name: " . $row["name"]. "<br>";
}
}
else
{
echo "query failure";
echo "Error: " . $sql . "<br>" . $conn->error;
}
$sql = "INSERT INTO companies (name)
VALUES ('mycompany')";
if ($conn->query($sql) === TRUE)
{
echo "insert success";
}
else
{
echo "insert failure";
echo "Error: " . $sql . "<br>" . $conn->error;
}

The problem is that a SELECT query will return a mysqli_result object on SUCCESS not a boolean TRUE. Only if the query fails, will it return a boolean FALSE;
Therefore you should use it like this :
$result = $conn->query($sql);
if ($result !== FALSE){
while($row = $result->fetch_assoc())
{
echo "ID: " . $row["ID"]. " - Name: " . $row["name"]. "<br>";
}
}

just change your if condition :-
if ($result = $conn->query($sql))
{
echo "query success";
while($row = $result->fetch_assoc())
{
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
}

Related

PHP - How to verify record deleted successfully

This is the code I'm using for deleting row from my DB:
<?php
$eid = $_GET['eid'];
$con = mysqli_connect("localhost", "root", "","project") or die("Connection failed");
echo "connection is done";
$query = "delete from exam where eid='$eid'";
if ($con->query($query)==TRUE)
{
echo " record deleted";
}
else
{
echo "Error: " . $query . "<br>" . $con->error;
}
$con->close();
?>
The else statement is not getting executed. It displays "record deleted" for every value even if the value is not found in the database.
Why is this happening? how can I verify that my record has been deleted from my DB?
You can use mysqli.affected-rows.
Consider the following:
$query="delete from exam where eid='$eid'";
if ($con->query($query)==TRUE && $con->affected_rows > 0) {
echo " record deleted";
} else {
echo "Error: " . $query . "<br>" . $con->error;
}

PHP - Echo'ing something from a MySQL DB [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 5 years ago.
I think, I might need help with my PHP code...
I'm trying to echo the info in a MySQL database and it gives me the Error: Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /usr/local/ampps/www/php/db.php on line 18
My code is:
<?php
$servername = "blabla"; //changed, connecting works
$username = "blabla";
$password = "blabla";
$database = "blabla";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
echo "Connection success \n";
}
$sql = mysql_query("SELECT * FROM Schueler");
while($data = mysql_fetch_array($sql)) //This is line 18...
{
echo "ID: " . $data['ID'] . " Vorname: " . $data['Vorname'] . " Nachname: " . $data['Nachname'] . " Klasse: " . $data['Klasse'] . "<br>";
}
$conn->close();
?>
Would be nice if somebody could help me :)
Edit:
I fixed it using MySqli only, this is my working code now:
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
echo "Connection success \n";
}
$sql = "SELECT ID, Vorname, Nachname FROM Schueler";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["ID"]. " - Name: " . $row["Vorname"]. " " . $row["Nachname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
Thanks for the quick advice.
You have used mysqli for your connection setup, then you used simple mysql functions to get the resultset and the fetch_array logic. You need to be uniform in this case.
I have changed the mysql_query() call to mysqli_query() call, and similarly the mysql_fetch_array() call to mysqli_fetch_array() call.
The final code becomes:
$sql = mysqli_query("SELECT * FROM Schueler", $conn);
while($data = mysqli_fetch_array($sql))
{
echo "ID: " . $data['ID'] . " Vorname: " . $data['Vorname'] . " Nachname: " . $data['Nachname'] . " Klasse: " . $data['Klasse'] . "<br>";
}

session verify isn't working after login

I've built a php login that verifies the user and redirects then to landing.php if successful. Otherwise, the login error is given to the user. Once on landing.php, I am trying to check that $_SESSION exists. If it does, then use a piece of it. If it doesn't it should redirect the user to the login page. However, if I directly type the landing.php url in the browser to skip the login, the page never redirects even though the $_SESSION is empty. Please advise to the best way to check the session.
MY CODE:
landing.php: (PHP Script)
<?php
session_start();
include('inc.php');
if (!(session_id())) {
header("Location: ['url']/index.php"); /*url not displayed for security*/
} else {
$welcome = "Welcome ".$_SESSION['userinfo']['firstname'];
}
?>
login.php: (Where session is created)
<?php
session_start();
include("inc.php");
if ((isset($_POST['username'])) and (isset($_POST['password']))) {
$login = $_POST['username'];
$pass = $_POST['password'];
} else {
//echo json_encode("Credentials did not save. Please try again.");
echo "Credentials did not save. Please try again.";
}
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_errno) {
//echo json_encode("There was a problem connecting to MySQL: (" . $conn->connect_errno . ") " . $conn->connect_error);
echo "There was a problem connecting to MySQL: (" . $conn->connect_errno . ") " . $conn->connect_error;
//echo json_encode("There was a problem connecting to MySQL.");
}
$sql = "SELECT * FROM sched_users WHERE login = ? ORDER BY login LIMIT 1";
if (!($sql = $conn->prepare("SELECT * FROM sched_users WHERE login = ? ORDER BY login LIMIT 1"))) {
//echo json_encode("Prepare failed: (" . $conn->errno . ") " . $conn->error);
echo "Prepare failed: (" . $conn->errno . ") " . $conn->error;
//echo json_encode("Prepare failed.");
}
if (!($sql->bind_param("s", $login))) {
//echo json_encode("Binding parameters failed: (" . $sql->errno . ") " . $sql->error);
echo "Binding parameters failed: (" . $sql->errno . ") " . $sql->error;
//echo json_encode("Binding parameters failed.");
}
if (!$sql->execute()) {
//echo json_encode("Execute failed: (" . $sql->errno . ") " . $sql->error);
echo "Execute failed: (" . $sql->errno . ") " . $sql->error;
//echo json_encode("Execute failed.");
}
$res = $sql->get_result();
if ($res->num_rows === 0) {
//echo json_encode("No user record found.");
echo "No user record found.";
} else if (!(($res->num_rows === 1) or ($res->num_rows === 0))) {
//echo json_encode("Too many results returned.");
echo "Too many results returned.";
} else {
$row = $res->fetch_array();
$hash = $row['password'];
if (password_verify($pass, $hash)) {
/*
$session = true;
echo json_encode($session);
*/
$_SESSION['userinfo']['firstname'] = $row['firstname'];
$_SESSION['userinfo']['lastname'] = $row['lastname'];
$_SESSION['userinfo']['email'] = $row['email'];
$_SESSION['userinfo']['phone'] = $row['phone'];
$_SESSION['userinfo']['company'] = $row['company'];
$_SESSION['userinfo']['department'] = $row['department'];
$_SESSION['userinfo']['admin'] = $row['admin'];
$_SESSION['userinfo']['statusflag'] = $row['statusflag'];
$_SESSION['userinfo']['revoked'] = $row['revoked'];
header("location: [url]/landing.php");/*url not displayed for security*/
} else {
//$session = false;
//echo json_encode($session);
//echo json_encode("The username or password does not match. Please try again.");
echo "The username or password does not match. Please try again.";
}
}
$sql->close();
$conn->close();
?>
This is your problem:
session_start();
...
if (!(session_id())) {
As soon as you start your session, you will have a session ID so the condition !(session_id() will always be false.
You should check for the content of the session instead, for example:
if (!array_key_exists('userinfo', $_SESSION)) {
...

reading data from mysql and displaying it in php

I'm trying to read from my database and display the info in my browser but it shows up a blank page,how do i fix this?
This is my html form:
This is my php script:
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['submit'])){
$sql = "SELECT * FROM mydb";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "name: " . $row["name"]. " - email: " . $row["email"]. " " . $row["phone"]. "<br>";
}
} else {
echo "0 results";
}
}
$conn->close();
?>
Thank you in advance

MySQL data on PHP Table - Online status different color label

Currently I am using this script
<?php
$servername = "**CENCERED**";
$username = "**CENCERED**";
$password = "**CENCERED**";
$dbname = "**CENCERED**";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT userID, users_name, usertype, status FROM tbluseraccounts";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["userID"]. " <br> Name: " . $row["users_name"]. " <br> Account Type: " . $row["usertype"]. " <br> Status: " . $row["status"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
How can I add to the code so when $row["status"] say "Online" my text will be green or when it says "Offline" It will turn Red.
In your while loop you can do something like
while($row = $result->fetch_assoc()) {
if($row["status"] == "Online"){
$tcolor = "green";
}
elseif($row["status"] == "Offline"){
$tcolor = "red";
}
echo "ID: " . $row["userID"]. " <br> Name: " . $row["users_name"]. " <br> Account Type: " . $row["usertype"]. " <br> Status: <font color='".$tcolor."'>" . $row["status"]. "</font><br>";
}
Hope this can give you some idea.

Categories