im failing to connect to my website database via php - php

So i was following a tutorial on how i can create a website with a database using php and wamp
and am failing on connecting my website to my database
this is the code i wrote
<?php
require ("Entities/CoffeeEntity.php");
class CoffeeModel {
function GetCoffeeTypes() {
require 'Credentials.php';
$mysqli = new mysqli("$servername", "$username", "$password", "$dbname");
$result = $mysqli->query("Select a distinct Cofffee");
$types = array();
while ($row = $result->fetch_assoc()) {
array_push($types, $row[0]);
}
mysql_close();
return $types;
}
function GetCoffeeByType($type) {
require 'Credentials.php';
$mysqli = new mysqli("$servername", "$username", "$password", "$dbname");
$query = "SELECT * FROM coffee WHERE type LIKE '$type'";
$result = $mysqli->query("error");
$coffeeArray = array();
while ($row = $result->fetch_assoc()) {
$name = $row[1];
$type = $row[2];
$price = $row[3];
$roast = $row[4];
$country = $row[5];
$image = $row[6];
$review = $row[7];
$coffee = new CoffeeEntity(-1, $name, $type, $price, $roast, $country, $image, $review);
array_push($coffeeArray, $coffee);
}
mysql_close();
return $coffeeArray;
}
}
?>
and this is the error that i get
Edit:
ok so i figured out that i need to replace mysql to mysqli
and i tried but it still seems not working cause i guess am doing something wrong
this is the result i came through
<?php
require ("Entities/CoffeeEntity.php");
//Contains database related code for the Coffee page.
class CoffeeModel {
//Get all coffee types from the database and return them in an array.
function GetCoffeeTypes() {
require 'Credentials.php';
//Open connection and Select database.
$mysqli = new mysqli("$servername", "$username", "$password", "$dbname");
$result = $mysqli->query("Select a distinct Cofffee");
$types = array();
//Get data from database.
while ($row = $result->fetch_assoc()) {
array_push($types, $row[0]);
}
//Close connection and return result.
mysql_close();
return $types;
}
//Get coffeeEntity objects from the database and return them in an array.
function GetCoffeeByType($type) {
require 'Credentials.php';
//Open connection and Select database.
$mysqli = new mysqli("$servername", "$username", "$password", "$dbname");
$query = "SELECT * FROM coffee WHERE type LIKE '$type'";
$result = $mysqli->query("error");
$coffeeArray = array();
//Get data from database.
while ($row = $result->fetch_assoc()) {
$name = $row[1];
$type = $row[2];
$price = $row[3];
$roast = $row[4];
$country = $row[5];
$image = $row[6];
$review = $row[7];
//Create coffee objects and store them in an array.
$coffee = new CoffeeEntity(-1, $name, $type, $price, $roast, $country, $image, $review);
array_push($coffeeArray, $coffee);
}
//Close connection and return result
mysql_close();
return $coffeeArray;
}
}
?>
and this error shows up
can someone please help and make it work (sorry am really bad at this )

The query() method returns false one failure, see: https://www.php.net/manual/en/mysqli.query.php
You must check the method's result before calling fetch_assoc().
Your query is failing because the first argument of the method must be a valid query while you are passing the string error, because of that you are trying to call a method on a boolean.
Try changing line 36 with $result = $mysqli->query($query);

Related

How to write to mysql database?

I used localhost and everything works fine, however, when I hosted it in digital ocean, certain POST functions don't write to the mysql database.
I've tried using Postman to test the code, and it returns 200 OK and error writing to database.
My db_functions code:
public function insertNewListing($name,$imgPath,$price,$listingId,$descriptions,$packageOne,$packageTwo,$moreDescriptions,$itinerary,$imgPathTwo,$imgPathThree)
{
$stmt= $this->conn->prepare("INSERT INTO `Longhouses`(`Name`, `Link`,`Price`,`ListingId`,`descriptions`,`PackageOne`,`PackageTwo`,`MoreDescription`,`Itinerary`,`ImageTwo`,`ImageThree`) VALUES (?,?,?,?,?,?,?,?,?,?,?)") or die ($this->conn->error);
$stmt->bind_param("sssssssssss",$name,$imgPath,$price,$listingId,$descriptions,$packageOne,$packageTwo,$moreDescriptions,$itinerary,$imgPathTwo,$imgPathThree);
$result = $stmt->execute();
$stmt->close();
if($result)
return true;
else
return false;
}
My add_listing function:
<?php
require_once '../../db_functions.php';
$db = new DB_Functions();
if(isset($_POST['name'])&&isset($_POST['imgPath'])&&isset($_POST['price'])&&isset($_POST['listingId'])&&isset($_POST['descriptions'])&&isset($_POST['packageOne'])&& isset($_POST['packageTwo'])&&isset($_POST['moreDescriptions'])&& isset($_POST['itinerary'])&& isset($_POST['imgPathTwo'])&& isset($_POST['imgPathThree']))
{
$name = $_POST['name'];
$imgPath = $_POST['imgPath'];
$price = $_POST['price'];
$listingId = $_POST['listingId'];
$descriptions = $_POST['descriptions'];
$packageOne = $_POST['packageOne'];
$packageTwo = $_POST['packageTwo'];
$moreDescriptions = $_POST['moreDescriptions'];
$itinerary = $_POST['itinerary'];
$imgPathTwo = $_POST['imgPathTwo'];
$imgPathThree = $_POST['imgPathThree'];
$result = $db->insertNewListing($name,$imgPath,$price,$listingId,$descriptions,$packageOne,$packageTwo,$moreDescriptions,$itinerary,$imgPathTwo,$imgPathThree);
if($result)
echo json_encode("ADD LISTING SUCCESFUL");
else
echo json_encode("error writing to database");
}

Computing sum of 2 fields in a table using MySQL fetch function in PHP

I have a table having the following fields: id(Autoincrement/Primary Key)/Integer1/Integer2/Sum/Product). I have filled integer1 and integer2 with the following code:
for ($i=1;$i<=1000;$i++)
{
$x2=rand(0,100);
$x3=rand(0,100);
$sql="INSERT INTO data(integer1,integer2) VALUES ($x2,$x3)";
$conn->query($sql);
}
I need help to prepare a function which uses MySQLFetch and computes sum of integer1 and integer2 and assigns the value in sum and product. I know it can be done using a simple loop, but would really like to get an understanding of fetching data.
Assuming you are using mysqli which is how it appears with the use of $conn->query() then this might be of interest.
/* establish db connection */
$dbhost = 'localhost';
$dbuser = 'root';
$dbpwd = 'xxx';
$dbname = 'xxx';
$conn = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
/* select records to to perform sum & product upon */
$sql='select * from `data`';
$res=$conn->query( $sql );
if( $res ){
/* prepare a new sql statement to update db records */
$sql='update `data` set `sum`=?, `product`=? where `id`=?;';
$stmt=$conn->prepare( $sql );
while( $rs=$res->fetch_object() ){
/* make some variables with records for each record */
$id=$rs->id;
$int_1=$rs->integer1;
$int_2=$rs->integer2;
/* basic maths operations */
$sum=$int_1+$int_2;
$product=$int_1 * $int_2;
/* bind the variables into declared statement & execute */
$stmt->bind_param( 'iii', $sum, $product, $id );
$stmt->execute();
}
/* tidy up */
$stmt->close();
$conn->close();
}
Kindly try the following example :
$db = new mysqli('localhost', 'root', 123456, 'data');
$query = 'SELCT * FROM tableName';
$objResult = $db->query($query);
while ($resultRow = $objResult->fetch_object()) {
$id = $resultRow->id;
$integer1 = $resultRow->integer1;
$integer2 = $resultRow->integer2;
$result = sumProduct($integer1, $integer2);
$sum = $result[0];
$product = $result[1];
$query = "UPDATE tableName SET
sum = '$sum',
product = '$product'
WHERE
id = $id";
$db->query($query);
$db->close();
}
function sumProduct($int1, $int2) {
$sum = $int1 + $int2;
$product = $int1 * $int2;
return array($sum, $product);
}
Is this way you expected?
$query = "SELECT * FROM data";
$row = mysql_query($query);
while($result = mysql_fetch_assoc($row))
{
$id = $result['id'];
$integer1 = $result['integer1'];
$integer2 = $result['integer2'];
$sum = $integer1 + $integer2;
$prod = $integer1 * $integer2;
mysql_query("UPDATE data SET sum=$sum,product=$prod WHERE id=$id");
}

Adding parameters to an already working webservice

I have the following already working great, but would like to add a parameter as this returns the whole data set.
<?php
$mysql_db_hostname = "localhost";
$mysql_db_user = "00000";
$mysql_db_password = "00000";
$mysql_db_database = "000000";
$con = #mysqli_connect($mysql_db_hostname, $mysql_db_user, $mysql_db_password,
$mysql_db_database);
if (!$con) {
trigger_error('Could not connect to MySQL: ' . mysqli_connect_error());
}
$var = array();
$sql = "SELECT * FROM mns";
$result = mysqli_query($con, $sql);
while($obj = mysqli_fetch_object($result)) {
$var[] = $obj;
}
echo '{"mns":'.json_encode($var).'}';
?>
For clarification, I was hoping to add a parameter in the url that is passed through to the php so that I get specific records. For example, if there is a field called [Customer], I would like to pass a customer id to it.

PHP infinite loop issue

I can get the correct code to work, but i want to be able to use objects and methods, which doesn't work. The same entry in the database is repeated until the query crashes. I saw other people that had queries inside of the while statement, but i thought that the method i am using should only query the statement once, but im likely wrong. Thanks.
<?php
include '/functions/MySQL.php';
$MySQL = new MySQL;
$con = mysqli_connect("host","user","password","db");
$result = mysqli_query($con,"SELECT * FROM reportLogger WHERE Moderator='jackginger'");
while($row = mysqli_fetch_array($MySQL->getReports('jackginger'))) {
$time = $row['Time'];
$moderator = $row['Moderator'];
$reason = $row['Reason'];
// Now for each looped row
echo "<tr><td>".$time."</td><td>".$moderator."</td><td>".$reason."</td></tr>";
}
?>
Seperate class
public function __construct(){
$this->con = mysqli_connect("localhost","root","pass","Minecraft");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
}
public function getUUID($username) {
$result = mysqli_query($this->con,"SELECT UUID FROM loginLogger WHERE Username='" . $username . "'");
return mysqli_fetch_array($result)[0];
}
public function getReports($username) {
$result = mysqli_query($this->con,"SELECT * FROM reportLogger WHERE UUID='" . $this->getUUID($username) . "'");
return $result;
}
Each time you call while($row = mysqli_fetch_array($MySQL->getReports('jackginger'))) you are making a new query, so it's fetching the samething over and over again.
a solution could be:
<?php
include '/functions/MySQL.php';
$MySQL = new MySQL;
$con = mysqli_connect("host","user","password","db");
$result = mysqli_query($con,"SELECT * FROM reportLogger WHERE Moderator='jackginger'");
$store = $MySQL->getReports('jackginger');
while($row = mysqli_fetch_array($store)) {
$time = $row['Time'];
$moderator = $row['Moderator'];
$reason = $row['Reason'];
// Now for each looped row
echo "<tr><td>".$time."</td><td>".$moderator."</td><td>".$reason."</td></tr>";
}
?>

MySQL select using an array

I edit my code working good but still one problem ... the data that selected from my database and displayed in my suggestion input ( only one row and last ID ) !!! How can I do it to display all data rows from my database ????
<?php
$q = strtolower($_GET["q"]);
if (!$q) return;
$host = "localhost";
$user = "root";
$password = "";
$database = "private_message_system";
//make connection
$server = mysql_connect($host, $user, $password);
$connection = mysql_select_db($database, $server);
$query = mysql_query("SELECT * FROM users");
while($row = mysql_fetch_array($query)){
$items = array($row["user_name"] => $row["user_email"]);
}
$result = array();
foreach ($items as $key=>$value) {
if (strpos(strtolower($key), $q) !== false) {
array_push($result, array(
"name" => $key,
"to" => $value
));
}
}
echo json_encode($result);
?>
As I know mysql doesn't have a array type like postgres so you have to fetch it one by one:
// here is where you get your to connection to the database
$conn = mysql_connect("your IP", "username", "password");
mysql_select_db("mydb", $conn);
// here you have to do the select to retrieve data from the table.
$query = "SELECT `name`, `to` from mytable";
// now you got all the records but you still need to iterate over this result
$result = mysql_query($query, $conn);
$array = array();
// retrieve a record and append it to the array
while($record = mysql_fetch_assoc($result)):
$array[] = $record;
endwhile;
// please close the door....
mysql_close($conn);
echo json_encode($array);
See below for a basic implementation of connecting to MySQL and searching for your $q, I've left a few comments for you to make it clearer what's going on!
<?php
// Get the query term from the url
$q = strtolower($_GET["q"]);
// Do nothing if it's empty or not set
if (empty($q)) return;
// Result array which we are going to get from MySQL
$result= array();
// Make a SQL Connection
mysql_connect("localhost", "admin", "password") or die(mysql_error());
// Try to connect to your DATABASE (change the name) or throw an error
mysql_select_db("DATABASE") or die(mysql_error());
// Get data from the "email" table
// Where the name field is LIKE the search term
$result = mysql_query("SELECT * FROM email WHERE name LIKE '%".mysqli_real_escape_string($q)."%'")
or die(mysql_error()); //throw an error if something went wrong
//Read all the results ($row) in a loop and put them in the result array
while($row = mysql_fetch_array( $result )) {
$result[] = array('name' => $row['name'], 'to' => $row['to']);
}
// Output the array as JSON
echo json_encode($result);
?>
For the more PHP experienced I am aware you can get an array from MySQL but have left it like this to make it clearer.
Enable error reporting
ini_set('display_errors', 1);
error_reporting(E_ALL);

Categories