I have been working on a website which has a xampp server and a database called users with a table called AccountDetails. About a year ago I got it to work perfectly, but the server I was using then required MySQL not MySQLi. Now I have to use MySQLi and can't even get the simplest of sql's SELECT function to work, any ideas would be much appreciated.
<?php
$link = mysqli_connect("localhost:3306", "root","", "users");
if(mysqli_connect_errno($link)){
echo "MySql Error: " . mysqli_connect_error();
} else {
echo"Connection Successful <br></br>";
}
echo("Check if still working <br></br>");
// -----------------------------//
echo("Its running <br></br>");
$result = $link->query("SELECT ID, UserName FROM AccountDetails");
return $result->result();
var_dump($result);
mysqli_close($link);
?>
The Query itself works when I plug it into the phpmyadmin SQL section and it returns the values that I expect it too.
I've spent days looking online for different answers but none of them work, and the var_dump only gives me "bool(false)" which I don't think I should be getting.
You can try this code
<?php
$link = mysqli_connect("localhost:3306", "root","", "users");
if(mysqli_connect_errno($link)){
echo "MySql Error: " . mysqli_connect_error();
} else {
echo"Connection Successful <br></br>";
}
echo("Check if still working <br></br>");
// -----------------------------//
echo("Its running <br></br>");
$sql_select = "SELECT * FROM AccountDetails";
$result = $link->query($sql_select);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "UserName: " . $row['UserName']. "<br>";
}
} else {
echo "No Records";
}
$link->close();
?>
Related
this is my first question here so feedback on how to improve my questions would be appreciated.
I am trying to display records from a database using PHP.
Here is the code
<?php
$dbConn = new mysqli('localhost', 'twa037', 'twa037Dg', 'autoservice037');
if($dbConn->connect_error) {
die("failed to connect to the database: " . $dbConn->connect_error);
}
else
{
echo "success";
}
$sql = "select * from customer ";
if ($dbConn->query($sql) )
{
echo "query successful";
}
while($row = $sql->fetch_assoc()) {
echo $row['familyName'];
}
$dbconn->close();
?>
I am able to connect to the database and also the query appears to be working fine as it is displaying "success" and "query successfull".
However, I am getting this error
Fatal error: Uncaught Error: Call to a member function fetch_assoc()
on string
Before you guys suggest this could be a duplicate of another post, I have noticed that in the other posts they have used the same code as I have without an issue.
mysqli_query returns a result on that you can call fetch_assoc(). not on the querystring itself.
if ($result = $dbConn->query($sql) )
{
echo "query successful";
}
while($row = $result->fetch_assoc()) {
more informations you can find here
while($row = $sql->fetch_assoc()) <=> while($row = $dbConn->query($sql)->fetch_assoc())
I'm trying to display data from my SQL database on a HTML page through a php query.
I've done a similar query before in the same way and that worked, however this php query doesn't display any results on my html page and I have no idea why.
<?php
$con=mysqli_connect("localhost","root","password","registration");
if (mysqli_connect_errno())
{
die("Failed to connect to MySQL: " . mysqli_connect_error());
}
$query = "SELECT * FROM goal WHERE id = $_SESSION[userid]";
$result = mysqli_query($con, $query);
if($result == false) {
die("Query failed: ".mysqli_error($con).PHP_EOL.$query);
}
while($row = mysqli_fetch_assoc($result))
{
echo "Weight Lost:"."<p>".$row['weightlost']."</p>\n";
echo "Weight Unit:"."<p>".$row['weightunit']."</p>\n";
echo "Date set for goal to be reached:"."<p>".$row['whenby']."</p>\n";
}
mysqli_close($con);
?>
I am doing a little bit of learning on mysql, php and the like. I'm using a shared hosting plan so am quite limited from a settings changes point of view.
I am attempting to run a simple mysql select command through PHP, but all i get back is a blank error
<?php
$typeID = $_GET['tid'];
//variables for the database server
$server = "localhost";
$user = "codingma_rbstock";
$pwd = "M#nL%V{%RI+h";
$db = "codingma_rbstock";
//variables for the database fields
$itemNo;
$itemNm;
$itemDesc;
$buyPr;
$sellPr;
$quan;
$dept;
//database connection
//create connection
$conn = new mysqli($server, $user, $pwd, $db);
//if the connection fails throw an error.
if ($conn->connect_error){
die("Connection Failed: " . $conn->connect_error);
}
echo "Welcome to " . $typeID . "<br>";
$sql = "select ITEM_NAME from stock where ITEM_NO='00001'";
if ($conn->query($sql) === TRUE){
$res = $conn->query($sql);
if ($res->num_rows > 0){
echo "success";
}
}else{
echo "Error: " .$sql . "<br>" . $conn->error;
}
echo $res;
?>
I have checked and it seems to be connecting to the database fine (I changed a few account details to see if that threw a different error and it did).
I am sure I am missing something completely obvious here! The below is the text output from the error;
Error: select ITEM_NAME from stock where ITEM_NO='00001'
Thanks for any help.
your problem is in this line
if ($conn->query($sql) === TRUE){
you are doing a variable type check ( === ), the result of that comparision will always fail because, for as long as you have data in your table and your query doesn't fail $conn->query($sql) will not return a boolean value
mysqli::query documentation says:
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.
You are using here a SELECT, therefore a successfull result won't be boolean
Try switching to
if ($conn->query($sql) == TRUE){
Or even better remove that if completely
EDIT
The better approach for that part of the code is:
$res = $conn->query($sql);
if ($res->num_rows > 0){
echo "success";
}
if ($res === false) {
echo "Error: " .$sql . "<br>" . $conn->error;
}
I'm just learning PHP and I thought it would be a good idea to learn some MySQL too.So I started working on the code and for some strange reason I keep getting duplicate users which is really really bad.
<?php
$link = mysqli_connect(here i put the data);
if(!$link)
{
echo "Error: " . mysqli_connect_errno() . PHP_EOL;
exit;
}
else
{
if(isset($_POST['user']))
{ echo "User set! "; }
else { echo "User not set!"; exit; }
if(isset($_POST['pass']) && !empty($_POST['pass']))
{ echo "Password set! "; }
else { echo "Password not set!"; exit; }
$num = mysqli_num_rows(mysqli_query("SELECT * FROM `users` WHERE ( username = "."'".$_POST['user']."' )"));
if($num > 0)
{ echo "Cannot add duplicate user!"; }
mysqli_close($link);
}
?>
For some strange reason I don't get the output I should get.I've tried some solutions found here on StackOverflow but they didn't work.
The first parameter of connectionObject is not given in mysqli_query:
$num = mysqli_num_rows(mysqli_query($link, "SELECT * FROM `users` WHERE ( `username` = '".$_POST['user']."' )"));
//----------------------------------^^^^^^^
Also, your code is vulnerable to SQL Injection. A simple fix would be:
$_POST['user'] = mysqli_real_escape_string($link, $_POST['user']);
mysqli_query must receive two parameters in order to work. In this case, your mysqli_connect.
$num = mysqli_num_rows(mysqli_query($link, "SELECT * FROM `users` WHERE ( username = "."'".$_POST['user']."' )"));
Also, you can be affected by SQL Injection, in this code.
Never add user input directly in your queries without filtering them.
Do that to make your query more readable and safe:
$u_name=mysqli_real_escape_string($link, $_POST['user']);
$num = mysqli_num_rows(mysqli_query($link, "SELECT * FROM `users` WHERE ( username = '$u_name' )"));
To use mysqli_* extension, you must include your connection inside of the parameters of all queries.
$query = mysqli_query($link, ...); // notice using the "link" variable before calling the query
$num = mysqli_num_rows($query);
Alternatively, what you could do is create a query() function within your website, like so:
$link = mysqli_connect(...);
function query($sql){
return mysqli_query($link, $sql);
}
and then call it like so:
query("SELECT * FROM...");
This could be a problem of race condition.
Imagine that two users wants to create the same username at the same time.
Two processes will execute your script. So both scripts select from database and find out that there is not an user with required username. Then, both insert the username.
Best solution is to create unique index on username column in the database.
ALTER TABLE users ADD unique index username_uix (username);
Then try insert the user and if it fails, you know the username exists ...
Here's how to write your code using prepared statements and error checking.
Also uses a SELECT COUNT(*)... to find the number of users instead of relying on mysqli_num_rows. That'll return less data from the database and just seems cleaner imo.
<?php
$link = mysqli_connect(here i put the data);
if(!$link) {
echo "Error: " . mysqli_connect_errno() . PHP_EOL;
exit;
}
else if(!isset($_POST['user'])) {
echo "User not set!"; exit;
}
echo "User set! ";
if(!isset($_POST['pass']) || empty($_POST['pass'])) {
echo "Password not set!"; exit;
}
echo "Password set! ";
$query = "SELECT COUNT(username)
FROM users
WHERE username = ?";
if (!($stmt = $mysqli->prepare($query))) {
echo "Prepare failed: (" . mysqli_errno($link) . ") " . mysqli_error($link);
mysqli_close($link);
exit;
}
$user = $_POST ['user'];
$pass = $_POST ['pass'];
if(!mysqli_stmt_bind_param($stmt, 's', $user)) {
echo "Execute failed: (" . mysqli_stmt_errno($stmt) . ") " . mysqli_stmt_error($stmt);
mysqli_stmt_close($stmt);
mysqli_close($link);
exit;
}
if (!mysqli_execute($stmt)) {
echo "Execute failed: (" . mysqli_stmt_errno($stmt) . ") " . mysqli_stmt_error($stmt);
mysqli_stmt_close($stmt);
mysqli_close($link);
exit;
}
$result = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_array($result, MYSQLI_NUM)) {
$num = $row[0];
if($num > 0) {
echo "Cannot add duplicate user!";
}
}
mysqli_stmt_close($stmt);
mysqli_close($link);
please do suggest fixes to syntax, this was typed from a phone
For some reason I made a query and the the query isn't executing, I tested it in the code to see if the query would execute and if it can't, to display a message and it displays the message.
I will post all the information below!
$_POST:
Code:
ini_set('display_errors',1);
error_reporting(E_ALL);
echo "<pre>";
var_dump($_POST);
echo "</pre>";
$mysqli = new mysqli("localhost", "lunar_casino", "******", "lunar_casino");
if(isset($_POST['submit'])){
$error = array();
if(empty($error)){
$bonus = $_POST['bonus'];
$deposit = $_POST['deposit'];
$offers = $_POST['offers'];
$link = $_POST['link'];
$name = $_POST['logo'];
$q = $mysqli->query("INSERT INTO `lunar_casino`.`casino` VALUES(NULL, '$bonus', '$deposit', '$offers', '$link', '$logo', '$name', NULL)");
if(!$q){
echo "<font color='red'><b>There has been an error with our database! Please contact the website administrator!</b></font><br /><br />";
} else {
echo "<font color='green'><b>You have successfully added the casino!</b></font><br /><br />";
}
} else {
echo "<font color='red'><b>There were ".count($error)." errors in your form:</b></font><br />";
foreach($error as $err){
echo "<b>".$err."</b><br />";
}
echo "<br />";
}
}
Structure of Database:
If you need more information just let me know!
By the way, the way I know the error is in the query is because I checked if(!$q) and made it display an error message if the query can't be done, and it displays the error message on the page.
Any ideas why its not working? Also I left out date from the query because I don't know how to add the current date:time into the query.
If anyone could help with either of these issues please let me know! :)
Start by checking for errors on connection
e.g
$db = new mysqli('localhost', 'user', 'pass', 'lunnar_casino');
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
Then execute your query and make sure you're using mysqli errors function to return occurred errors
e.g
$sql = <<<SQL
SELECT *
FROM `students`
WHERE `marks` < 10
SQL;
if(!$result = $db->query($sql)){
die('An error occured [' . $db->error . ']');
}
Let me know if this worked for you, I will add more information if needed.