Cannot get mysql query to wok - php

I am trying to query the table bets but it seems it is not returning anything, even though there is data in it which matches the criteria
I'm not sure if I'm missing something completely obvious or not
Here is my code,
<?php
//Begin session
session_start();
//Get pool var
if(isset($_GET['pool'])) {
$_SESSION['pool'] = $_GET['pool'];
$pool = $_SESSION['pool'];
}
//Include database connection details
require_once('config.php');
//Array to store validation errors
$errmsg_arr = array();
//Validation error flag
$errflag = false;
//Connect to mysql server
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
//Assign memberid
$memberid = $_SESSION['SESS_MEMBER_ID'];
echo "POOLNAME $pool<br>";
echo "MEMBERID $memberid<br>";
//Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
$result = mysql_query($link,"SELECT * FROM bets WHERE member_id='$memberid'");
echo "RESULT $result";
echo "SQL executed<br>";
echo "Executing loop<br>";
while($row = mysql_fetch_array($result))
{
echo "test<br>";
$matchid = $row['match_id'];
$betAmount = $row['bet_amount'];
$teamname = $row['team_name'];
echo "$betAmount credits placed on team: $teamname for match: $matchid";
}
?>

You are mixing mysql and mysqli commands. You need to use one or the other, preferably mysqli, if possible.
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
should be:
$link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
And in mysqli_fetch_array() the first parameter is the mysqli result object (which you have correctly) and it requires a second parameter for the array it will return., MYSQLI_BOTH for example.
MYSQLI_BOTH will allow you to reference the array by the number indices or the column name
MYSQLI_ASSOC will allow reference from column names but not number indices and MYSQLI_NUM allows number indices.
so while ($row = mysqli_fetch_array($result, MYSQLI_BOTH)) would be what you want.
Also, do refer to the comment from Andy Lester about SQL injection, it is very important to sanitize input.

Related

Null return from localhost php coding

I set up my localhost, I have all my relevant files in place. I run the php where I run the sql query, it returns NULL values. But it should not. I visit to the directory of the link via browser.
Can someone point me in the return direction, why it is returning NULL? I ran the SQL query, and works fine on my phpmyAdmin
<?php
header('Content-Type: application/json');
define('DB_HOST', '127.0.0.1');
define('DB_USERNAME', 'myusername');
define('DB_PASSWORD', 'Ihavenopassword');
define('DB_NAME', 'mytablename');
$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
//$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if(!$mysqli){
die("Connection failed: " . $mysqli->error);
}
//query to get data from the table
$query = sprintf("SELECT playerid, score FROM score ORDER BY playerid");
//execute query
$result = $mysqli->query($query);
//loop through the returned data
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
//free memory associated with result
$result->close();
//close connection
$mysqli->close();
//now print the data
print json_encode($data);
$result is not what you expect. You need to fetch every item, with fetch_assoc for example:
//loop through the returned data
$data = array();
while ($row = $result->fetch_assoc()) {
$data[] = $row;
}

Show all tables within given MySQL database

I'm trying to show all tables within a given MySQL database with php.
I'm very new to all this though and can't find a solution for it. Keeps giving an error 'no found file or directory'.
Anyone who can point out my mistakes here please?
Much appreciated!
<?php include "../inc/dbinfo.inc"; ?>
<html>
<body>
<h2>LIST TABLES FROM DATABASE</h2>
<?php
// Create connection
$conn = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD);
// Check connection
if ($conn->connect_error) {
die("Connection with the database failed: </br>" . $conn->connect_error);
}
echo "Connection established with the database! </br>";
// SQL to show tables
$sql = "SHOW TABLES FROM paperlessdb";
$result = mysql_query($sql);
if (!$result) {
echo "Database error, could not list tables.\n</br>";
echo 'MySQL error: ' . mysql_error();
exit;
}
while ($row = mysql_fetch_row($result)) {
echo "- {$row[0]}\n </br>";
}
mysql_free_result($result);
?>
First make up your mind, either use mysqli procedural or object orientated. Not a combination of both because its confusing. To avoid that all together use pdo instead.
Now properly connect to the database, you can select the database when connecting to it automatically:
const DB_DATABASE = 'paperlessdb';
$conn = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
// Check connection
if ($conn->connect_error) {
die("Connection with the database failed: </br>" . $conn->connect_error);
}
if($result = $conn->query('SHOW TABLES')){
while($row = $conn->fetch_array($result)){
$tables[] = $row[0];
}
}
print_r($tables);
Use below query,
$sql = "SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'paperlessdb'";
We are fetching the data from information_schema db which stores the meta data about our database.
You are using mysqli to connect to the database but use the depreciated mysql to query the database.
$conn = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD);
$result = mysql_query($sql);
while ($row = mysql_fetch_row($result)){}
mysql_free_result($result);
You should use mysqli_query() and mysqli_fetch_array() instead.
It'a a bit more complex but mysql is decrecated and remove as PHP 7 so no choice to jump ahead. Check out PDO ass well. I personally go for mysqli but most say pdo is more intuitive.
It should look more something like:
$result = mysqli_query($conn,$sql);
if(!$result){
die('MySQL error: ' . mysqli_error($conn));
}
while ($row = mysqli_fetch_row($result)) {
echo "- {$row[0]}\n </br>";
}

Select SQL query is not working in PHP

I am having trouble with an SQL query that I have inserted into a piece of PHP code to retrieve some data. The query itself works perfectly within SQL. I am using the following PHP script.
I have the following objectives:
Connect to the existing database. This part works well.
Get data from the column 'Brand' of the table 'Transport' in $sql. This part is not working at this stage. echo ($sql) returns SELECT Brand FROM Transport WHERE Type = 'car'
Could you please let me know if you see the solution to this issue and if the remaining part of the code is correct. This is my f_sqlConnect()
function f_sqlConnect() {
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!link) {
die('Could not connect: '.mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);
if (!$db_selected) {
die('Can not use'.DB_NAME.
': '.mysql_error());
}
}
/*This function cleans up the array to protect against injection attacks */
function f_clean($array) {
return array_map('mysql_real_escape_string', $array);
}
<?php
// Create connection
$link = f_sqlConnect();
// Getting data from the column Brand of the table Transport
$sql = "SELECT Brand FROM Transport WHERE Type = 'car'";
$result = $link->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "Brand: " . $row["Brand"]. "<br>";
}
} else {
echo "0 results";
}
$link->close();
?>
Here is the code, without seeing your f_sqlConnect(); mothod. This method should return connection string for DB in your case. But you can use following code this must work.
<?php
$servername = "Your_db_host";
$username = "your_db_username";
$password = "your_db_password";
$dbname = "your_DB_name";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Brand FROM Transport WHERE Type = 'car'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "Brand: " . $row["Brand"];
}
} else {
echo "0 results";
}
$conn->close();
?>
NOTE: Object oriented way of mysqli, You can use procedural way too to connect and get data.

Query MySQL with PHP

I am trying to query a MySQL database with PHP and return the results as JSON. I'm new to PHP and web development so I'm not sure what I'm doing wrong. I've set up the database using MAMP. My parameters are being printed but I'm not getting the JSON. I've gotten this far with the help of a tutorial.
EDIT: I just went into phpMyAdmin to make sure it was working and when I click on Server:localhost:8889, a window pops up that says Error in processing request. Error code 404.
I'm thinking this is the problem, I'm just not sure why it isn't working. I may reinstall MAMP.
<?php
$user = 'root';
$password = 'root';
$db = 'TestDB';
$host = '127.0.0.1';
$port = '8889';
$first_name = filter_input(INPUT_GET, 'first_name');
$last_name = filter_input(INPUT_GET, 'last_name');
$membership_number = filter_input(INPUT_GET, 'membership_number');
echo $first_name;
echo $last_name;
echo $membership_number;
// Create connection
// $con = mysqli_connect("localhost", "root", "root", "TestDB");
// $con = mysqli_connect("localhost", "root", "root", "TestDB", "8889", $socket);
$link = mysqli_init();
$con = mysqli_real_connect($link, $host, $user, $password, $db, $port);
// Check connection
if(mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM NAME WHERE FIRST_NAME = \'$first_name\' and LAST_NAME = \'$last_name\' and MEMBERSHIP_NUMBER = \'$membership_number\'";
$result = mysqli_query($con, $sql);
if(!$result) {
die('Query failed: ' . mysqli_error());
}
// Check for results
// if ($result = mysqli_query($con, $sql)) {
if($result) {
// If there are results, create results array and a temporary one to hold the data
$resultArray = array();
$tempArray = array();
// Loop through each row in the result set
// while($row = $result->fetch_object()) {
while($row = mysqli_fetch_object($result)) {
// Add each row to the results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
echo $tempArray;
echo $resultArray;
echo $result;
echo json_encode($resultArray);
}
// Close connections
mysqli_close($con);
?>
You need to change you $sql variable to remove the escapes on the single quotes. They register as part of the string because you are using double-quotes to wrap it. Basically, you're telling the database to run the query "SELECT * FROM NAME WHERE FIRST_NAME = \'John\' and LAST_NAME = \'Smith\' and MEMBERSHIP_NUMBER = \'VRX78435\'". This will error if you run it directly because the escape characters are not escaping.
$sql = "SELECT * FROM NAME WHERE FIRST_NAME = '$first_name' and LAST_NAME = '$last_name' and MEMBERSHIP_NUMBER = '$membership_number'";
That should fix it for you.
There may also be an issue with your connection to the server. mysqli_query() uses the results of mysqli_connect() to run the query. mysqli_real_connect() only returns a boolean value, so it is invalid for this particular use (at least it failed to work on my server).
This would be a simple matter of replacing the $con and then you can drop the $link variable.
$con = mysqli_connect($host, $user, $password, $db, $port);
These changes, and assuming the $first_name, $last_name, and $membership_number are all valid, allowed your script to run for me, so I hope this helps.
Seems you are using procedural style coding
Instead of
while($row = $result->fetch_object()) {
You need mysqli_fetch_object in procedural style
while($row = mysqli_fetch_object($result)) {

connect to sql database with php

Im trying to connect to sql database with PHP.For some reason when i run the code i am getting below error.
Parse error: syntax error, unexpected '$result' (T_VARIABLE) in C:\xampp2\htdocs
\tutorials\abb.php on line 13
My Code is this...
$user = 'root' ;
$pass = 'xcvsdffd' ;
$db = 'testdb' ;
$con = new mysqli('localhost', $user , $pass , $db) or die("UNABLE TO CONNECT");
$selected = mysql_select_db($db,con)
$result = mysql_query("SELECT * FROM test");
while ($row = mysql_fetch_array($result)) {
echo "ID:".$row{'id'}." Name:".$row{'name33'}."
".$row{'year'}."<br>";
}
//close the connection and recordset objects freeing up resources
$result->Close();
$con->Close();
$result = null;
$con = null;
?>
There are two reasons which was the reason for your errors..
1.
You missed a semicolon ; and a $ sign. Below is valid one.
$selected = mysql_select_db($db,$con); //Replace this with your existing line.
2.
You are mixing mysql_* and mysqli_*
Sidenote:
This(mysql_*) extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. Switching to PreparedStatements is even more better to ward off SQL Injection attacks !
The PDO way...
<?php
$dsn = 'mysql:dbname=testdb;host=localhost';
$user = 'root';
$password = 'xcvsdffd';
try
{
$dbh = new PDO($dsn, $user, $password ,array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
For more information.. read the PHP Manual. or use PreparedStatements in MySQLi
Mysqli works with MySQL version 4.1.13 or newer; if your version is old then u should connect your db the old way like this:
$con=mysql_connect("localhost","root","pass");
mysql_select_db("database_name",$con);
They always tell me that MySQL command is now depreciated or something. That's why it's a good practice to use PDO or MySQLI. It's easy to use, if you'll appreciate it's use.
Now going to your code:
$connection = new mysqli("localhost","user","password","database name");
$selectDatabase = mysqli_select_db($connection,"database name");
$connection->query ("SELECT * FROM test");
Hope this helps
Try this below , if you are creating mysqli connection then you dont have to use mysql_select_db($db,con) for again select database. or use semicolon after this line
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* return name of current default database */
if ($result = $mysqli->query("SELECT DATABASE()")) {
$row = $result->fetch_row();
printf("Default database is %s.\n", $row[0]);
$result->close();
}
/* change db to world db */
$mysqli->select_db("world");
/* return name of current default database */
if ($result = $mysqli->query("SELECT DATABASE()")) {
$row = $result->fetch_row();
printf("Default database is %s.\n", $row[0]);
$result->close();
}
$mysqli->close();
?>
Reference
there might be a semicolon missing in a line .
mysql_select_db($db,$con);
Try this
<?php
$username = 'root';
$pass = 'pass';
$db = 'db';
$link = mysqli_connect('localhost',$username,$pass,$db);
if(!link){
echo "Not Connected to DB" . mysqli_connect_error();
$result = mysqli_query($link, "SELECT * FROM test");
while($row = mysqli_fetch_array($result)){
echo "ID: " . $row['id'];
echo "Name: " . $row['name33'];
echo "Year: " . $row['year'];
}
?>
Querying in PHP must be consistent, meaning if you use mysqli you should use it throughout the PHP file, and if you use mysqli you must also use it throughout the PHP file. mysqli and mysql also has different code constructions. So search on the web for their proper construction. Hope this helps

Categories