No longer able to connect to mysql using PHP - php

I keep getting the following error:
Fatal error: Call to a member function fetch_array() on boolean in C:\xampp\htdocs\DeletePlayerSOLN\DeletePlayerExample_SOLN\index.php on line 10
Any idea what the problem is? I searched previous threads and tried to identify the problem for the past few hours. I'm new to PHP.
I'm using Xampp + Mysql.
MySQL connection:
127.0.0.1
3306
root
Default Schema: test
I'm connected through port 443,4433 through Xampp. So I try to connect through /localhost:443/folder..filename..
Connection:
//make a database connection object
$mysqli = new mysqli($server, $user, $pass, $database);
//test if there are database connection errors
if ($mysqli->connect_error)
die("Connect Error " . $mysqli->connect_error);
?>
Index page:
<?php
require "serverCode/connect.php";
$selectPlayer = "SELECT * FROM player ORDER BY playerLastName, playerFirstName";
$results = $mysqli->query($selectPlayer);
$ddlString = "<select name='cboPlayer' size='10'>";
while($row = $results->fetch_array())
{
$ID = $row["playerID"];
$name = $row["playerLastName"] . ", " . $row["playerFirstName"];
$ddlString .= "<option value='$ID'>$name</option>";
}
$ddlString .= "</select>";
$mysqli->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>DELETE Player Page</title>
</head>
<body>
<form name="frmPlayer" action="serverCode/deletePlayer.php" method="get">
Select a player:<p><?php echo $ddlString;?>
<input type="submit" name="btnSubmit"></p>
</form>
</body>
</html>
Line 10 is "while($row = $results->fetch_array())"

It is likely that $mysqli->query() is not producing a proper object due to an error. Try replacing
$results = $mysqli->query($selectPlayer);
with
$results = $mysqli->query($selectPlayer) or trigger_error($mysqli->error."[$selectPlayer]");

Related

Show Output/Echo of PHP File executing at load on webpage

im trying to create my first website and Im clueless in this case.
So I have a MySQL-Database with a table. And I have a php-File called database.php which reads from the database and echos all the lines of a query:
<?php
$servername = "xxxxxxxxxx.hosting-data.io";
$username = "xxxxxxxx";
$password = "xxxxxxx";
$dbname = "xxxxxxx";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT ID, Name, Beschreibung, Datum, Uhrzeit FROM Termine";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "ID: " . $row["ID"]. " - Name: " . $row["Name"]. " - Beschreibung: " . $row["Beschreibung"]. " - Datum: " . $row["Datum"]. " - Uhrzeit: " . $row["Uhrzeit"]."<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
Now on my index.php I want to execute this php-code on calling/loading the webpage and print all the lines (data entries).
But i have no idea how to get the echo (=data entries) of the php file printed in the body of my webpage. I read about AJAX and using a js-script but I still wasnt able to figure it out.
Thanks for your help.
Option 1: Place your PHP code inside the HTML body.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
echo 'Hello World';
// ...
?>
</body>
</html>
Option 2: Create a separate PHP file containing your code above and include/require it into your body.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
include_once('your_php_file.php');
?>
</body>
</html>
Option 3: Call your PHP file using an AJAX call (e.g. by using jQuery load()).
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="aDiv"></div>
<script> $( "#aDiv" ).load('your_php_file.php', function() { console.log('Loaded'); });</script>
</body>
</html>
If your index file is index.php then the PHP code will be run when you load the webpage. That is assuming, of course, that your web server (local or remote) has PHP installed.

PHP and MySQL database search - removing database credentials from php code [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 3 years ago.
I found some code for a simple database search using PHP and MySQL and I was able to make it work. However, I decided it might not be such a great idea to leave my database username and password in the PHP code within the root folder. So, I found another code sample that demonstrated how to create a config.ini file outside the root, and use a dbconnect.php file to access the database credentials. I tried to implement this, but I'm not having any luck and was wondering if someone could show me what I'm missing (I only have a rudimentary grasp of coding and am trying to learn little by little). I have included the code for all of the component files (and I changed any username/passwords/servernames to generic placeholders). Below the code I have pasted the errors that are currently being shown when I submit the search form. Thanks!
index.php:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Search</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<form action="search.php" method="GET">
<input type="text" name="query" />
<input type="submit" value="Search" />
</form>
</body>
</html>
search.php:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Search</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<?php require_once('./includes/dbconnect.php'); ?>
</head>
<body>
<?php
$query = $_GET['query'];
// gets value sent over search form
$min_length = 3;
// you can set minimum length of the query if you want
if(strlen($query) >= $min_length) { // if query length is more or equal minimum length then
$query = htmlspecialchars($query);
// changes characters used in html to their equivalents, for example: < to >
$query = mysql_real_escape_string($query);
// makes sure nobody uses SQL injection
$raw_results = mysql_query("SELECT * FROM details WHERE (`title` LIKE '%".$query."%') OR (`text` LIKE '%".$query."%')") or die(mysql_error());
// * means that it selects all fields
// details is the name of our table
// '%$query%' is what we're looking for, % means anything, for example if $query is Hello
if(mysql_num_rows($raw_results) > 0) { // if one or more rows are returned do following
while($results = mysql_fetch_array($raw_results)) {
// $results = mysql_fetch_array($raw_results) puts data from database into array, while it's valid it does the loop
echo "<p><h3>".$results['title']."</h3>".$results['text']."</p>";
// posts results gotten from database(title and text) you can also show id ($results['id'])
}
} else { // if there is no matching rows do following
echo "No results";
}
} else { // if query length is less than minimum
echo "Minimum length is ".$min_length;
}
?>
</body>
</html>
dbconnect.php:
<?php
function db_connect() {
// Define connection as a static variable, to avoid connecting more than once
static $connection;
// Try and connect to the database, if a connection has not been established yet
if(!isset($connection)) {
// Load configuration as an array. Use the actual location of your configuration file
$config = parse_ini_file('/home/cpanelusername/private/config.ini');
$connection = mysqli_connect($config['servername'],$config['username'],
$config['password'],$config['dbname']);
}
// If connection was not successful, handle the error
if($connection === false) {
// Handle error - notify administrator, log to a file, show an error screen, etc.
return mysqli_connect_error();
}
return $connection;
}
// Connect to the database
$connection = db_connect();
// Check connection
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
?>
config.ini:
[database]
servername = localhost
username = username
password = password
dbname = username_database
Warning: mysql_real_escape_string(): Access denied for user
'root'#'localhost' (using password: NO) in
/home4/cpanelusername/public_html/...../search.php on line 29
Warning: mysql_real_escape_string(): A link to the server could not be
established in /home4/cpanelusername/public_html/......./search.php on
line 29
Warning: mysql_query(): Access denied for user 'root'#'localhost'
(using password: NO) in
/home4/cpanelusername/public_html/......../search.php on line 33
Warning: mysql_query(): A link to the server could not be established
in /home4/cpanelusername/public_html/......./search.php on line 33
Access denied for user 'root'#'localhost' (using password: NO)
This is because mysql_real_escape_string takes into account the current character set of the connection. As such, it needs a connection. :-)
Please try to connect database using below code and please let me know if you have any problem.
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
Scrubbing the strings that come from userland isn't sufficient to prevent SQL injection attacks. The standard way is to use a prepared query. E.g.:
$stmt = mysqli_stmt_init($this);
$result = array();
$okay = mysqli_stmt_prepare($stmt, "SELECT * FROM details WHERE (title LIKE ?) OR (text LIKE ?)");
if ($okay)
$okay = mysqli_stmt_bind_param($stmt, "ss", "%$query%", "%$text%")
else
[handle error]
if ($okay)
$okay = mysqli_stmt_execute($stmt);
else
[handle error]
if ($okay)
$okay = mysqli_bind_result($stmt, $row);
else
[handle error]
if ($okay)
while (mysqli_stmt_fetch($stmt))
array_push($result, $row);
else
[handle error]
mysqli_stmt_close($stmt);

Connection to remote MS SQL database from Linux server using PHP

I have hosted my website on Linux server and I want to connect MS SQL database. i have used PHP in programming. I have contacted to both server provider and they helped in their extent. But my issue is not solved Can you guide me what to do. My code is below.
While I run this it is showing " could not find driver1"
Please guide me. Thanks in advance
<?php
//echo phpinfo();
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h1>testing</h1>
</body>
</html>
<?php
// Server in the this format: <computer>\<instance name> or
// <server>,<port> when using a non default port number
$server = 'server:port';
$myDB = "DatabaseName";
// Connect to MSSQL
$link = mssql_connect($server, 'username', 'password');
if (!$link) {
die('Something went wrong while connecting to MSSQL');
}
else
{
echo "success";
}
?>
<?php
try {
$conn = new PDO("sqlsrv:Server='server_name';Database=database_name", 'username', 'password');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $e) {
die(print_r($e->getMessage() ));
}
$tsql = "select * from table_name";
$getResults = $conn->prepare($tsql);
$getResults->execute();
$results = $getResults->fetchAll(PDO::FETCH_BOTH);
foreach ($results as $row) {
echo $row['0'].' '.$row['6'];
echo "<br>";
}
?>

Why isn't my mysql query from python shell going through to the web hosting database

ok so I have the following code that I am running in the python shell:
import MySQLdb
db = MySQLdb.connect(host = "xxxx",user="xxxx"password="xxxx",db="xxxx")
cur = db.cursor()
cur.execute(CREATE TABLE qqqq (asdf VARCHAR(20),fdsa VARCHAR(20))
Fairly sure the connection part is working, I'll get an error if I enter in the wrong value, or if I deny access to the database for my computer's IP address.
on the webhosting server, I have the following basic index.php file, which I have tested on a server on my computer, and I know works. when I go to the website domain, I get the following error: "Database query failed."
Any ideas why the MySQL query isn't working? My webhosting is Cpanel with godaddy.com, should I look for something else?
<?php
$dbhost = "xxxx";
$dbuser = "xxxx";
$dbpass = "xxxx";
$dbname = "xxxx";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname); /*1*/
if(mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}
?>
<?php
$query ="SELECT * FROM qqqq"; /*2*/
$result = mysqli_query($connection, $query);
if (!$result) {
die("Database query failed.");
}
?>
<!DOCTYPE html PUBLIC >
<html lang="en">
<head>
<title></title>
</head>
<body>
<ul>
<?php /*3*/
while($subject = mysqli_fetch_assoc($result)){
?><li><?php echo $subject['asdf'];?></li>
<?php
}
?>
</ul>
<?php
mysqli_free_result($result); /*4*/
?>
</body>
</html>
<?php
mysqli_close($connection); /*5*/
?>
You should call db.commit() to have it complete. By default, autocommit is turned off.
You also have an error in your code. The SQL should be a string.
Shouldn't the cursor execute be calling a string? You don't have quotes around your sql statement.
This line without quotas is incorrect:
cur.execute(CREATE TABLE qqqq (asdf VARCHAR(20),fdsa VARCHAR(20))
It should be
cur.execute("CREATE TABLE qqqq (asdf VARCHAR(20),fdsa VARCHAR(20))")
So test in your database whether you really have table qqqq.
You could install SQL Buddy or phpMyAdmin.

create new db in mysql with php syntax

I am trying to create a new db called testDB2, below is my code.
Once running the script all I am getting an error on line 7
Fatal error: Call to undefined function mysqlquery() in /home/admin/domains/domain.com.au/public_html/db_createdb.php on line 7
This is my code
<?
$sql = "CREATE database testDB2";
$connection = mysql_connect("localhost", "admin_user", "pass")
or die(mysql_error());
$result = mysqlquery($sql, $connection)
or die(mysql_error());
if ($result) {
$msg = "<p>Databse has been created!</p>";
}
?>
<HTML>
<head>
<title>Create MySQL database</title>
</head>
<body>
<? echo "$msg"; ?>
</body>
</HTML>
UPDATE, now I get error
Access denied for user 'admin_user'#'localhost' to database 'testDB2'
what does this mean?
The function is called mysql_query. Note the _

Categories