SQLi Error when trying to echo a certain ID in PHP - php

I am making a status update page for practicing PHP and MySQL.
I am currently trying to echo the saved status on the page.
The statuses are saved in a row called "Status" and they are all given a certain ID in a row called "statusID."
The problem I am having is which fetch I want to use because converting it into a string using (string)$var doesn't work. ($var is an example).
Also, the $idNum variable is something for later use, shouldn't have anything to do with this.
Here is the code: (Obviously the first variables are censored so none tries to connect to the database, the connection working in the actual code.)
The problem lies in the $fetchRes I believe.
<?php
$idNum = 1;
$servername = "censored";
$username = "censored";
$password = "censored";
$db_name = "censored";
$conn = mysqli_connect($servername, $username, $password, $db_name);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Status FROM SavedStatuses WHERE statusID=1;";
$statusQuery = mysqli_query($conn, $sql);
$fetchRes = mysqli_fetch_assoc($statusQuery);
if($conn->query($sql) == TRUE)
{
echo $fetchRes;
} else {
echo "Failed to retrieve status, error: " . $conn->error;
}
?>

As I mentioned in comments, you are querying twice and not looping over (successful) results.
A "loop" is to use either a while or a foreach. I used a while loop for this example.
From the "official" manual:
http://php.net/manual/en/mysqli-result.fetch-assoc.php
Example:
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";
if ($result = $mysqli->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}
/* free result set */
$result->free();
}
/* close connection */
$mysqli->close();
?>
So in your case, your code would read as:
Sidenote: Status and status are two different animals, so make sure the letter case matches (in the loop).
<?php
$mysqli = new mysqli("censored", "censored", "censored", "censored");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$query = "SELECT Status FROM SavedStatuses WHERE statusID=1";
if ($result = $mysqli->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
echo $row["Status"];
}
/* free result set */
$result->free();
}else{
echo "The query failed: " . mysqli_error($mysqli);
}
/* close connection */
$mysqli->close();
?>

Related

How to put data from database in a select box

I have a select box to gather the id numbers from the database, it's showing how much is in the database but the options are blank.
This is the code I have. I just want to be able to bring id number from my database in this select box.
php
<?php
$mysqli = new mysqli("localhost", "root", "", "volunteer");
/* check connection */
if (mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT * FROM registrations";
$result = mysqli_query($mysqli,$query);
while($rows = mysqli_fetch_assoc($result))
{
echo "<option value=" . $rows['idnumber'] . "></option>";
}
?>

I'm trying to echo data from DB using MySql and php

I'm trying to echo data from DB but it is showing 500 error. Same code works in some other server but it is not working in my present diff server.
<?php
error_reporting(0);
session_start();
$hostname_dbConn = "localhost";
$database_dbConn = "data_data";
$username_dbConn = "user_data";
$password_dbConn = "datauser";
$dbConn = mysql_pconnect($hostname_dbConn, $username_dbConn, $password_dbConn) or trigger_error(mysql_error(),E_USER_ERROR); mysql_select_db($database_dbConn, $dbConn);
$query_getconfig = "SELECT * FROM configuration WHERE status = 'A'";
$getconfig = mysql_query($query_getconfig, $dbConn) or die(mysql_error());
$row_getconfig = mysql_fetch_assoc($getconfig); $totalRows_getconfig = mysql_num_rows($getconfig);
?>
Remove error_reporting(0); and check what errors exactly are you facing?
Either #mysql_pconnect($hostname_explorecalirfornia, $username_explorecalirfornia, $password_explorecalirfornia) or trigger_error(mysql_error(),E_USER_ERROR); //# infront of mysql_pconnect or use below written code
$mysqli = new mysqli(HOST, USERNAME, PASSWORD, DBNAME);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
For fetch record.
$sql= "SELECT * FROM configuration WHERE status = 'A'";
// get the result object.
$result = $mysqli->query($sql);
// fetch the result row.
$data = $result->fetch_assoc();
return $data;
with mysqli
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";
$result=mysqli_query($con,$sql);
// Numeric array
$row=mysqli_fetch_array($result,MYSQLI_NUM);
printf ("%s (%s)\n",$row[0],$row[1]);
// Associative array
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
printf ("%s (%s)\n",$row["Lastname"],$row["Age"]);
// Free result set
mysqli_free_result($result);
mysqli_close($con);

get request returning empty json with valid parameter

so i have a database of Affiliates in the phpmyadmin of a site and i made a get api to get an specific affiliate given the id number, now i can connect and i make the call, but everytime i only get an empty json example
["","","","","",""]
doesnt matter if the id number is a valid one, an invalid one or even a letter, thats what i get every time
now here is my code for the connection
<?php
header( 'Content-Type: text/html;charset=utf-8' );
function ejecutarSQLCommand($commando){
$mysqli = new mysqli("ip", "user", "pass","database");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
if ( $mysqli->multi_query($commando)) {
if ($resultset = $mysqli->store_result()) {
while ($row = $resultset->fetch_array(MYSQLI_BOTH)) {
}
$resultset->free();
}
}
$mysqli->close();
}
function getSQLResultSet($commando){
$mysqli = new mysqli("ip", "user", "pass", "database");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
if ( $mysqli->multi_query($commando)) {
return $mysqli->store_result();
}
$mysqli->close();
}
?>
and here is the request file
<?php
include('function.php');
$id=$_GET["ID"];
if($resultset=getSQLResultSet("SELECT * FROM `table` WHERE ID='$id'")){
while ($row = $resultset->fetch_array(MYSQLI_NUM)){
echo json_encode($row);
}
}
?>
I made more realistic code. The next step would be making this into a class.
The prepare in stead of a query will protect against SQL injection also data with quotes in it.
index.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
include('function.php');
$id=$_GET["ID"];
dbConnect();
$rows = getSQLResultSet($id);
echo json_encode($rows);
dbClose();
function.php
<?php
//
// not sure if this is needed for returning json
//
header( 'Content-Type: text/html;charset=utf-8' );
//////////////////////////////////////////////////////////////////////////////////////////////////////
function dbConnect(){
//
// You should be gettng the db connect info from a source out side the webservers reach.
//
// read a ini file or imclude a file
//
$ip = '127.0.0.1';
$user = 'test';
$pass = 'test12';
$db = 'test';
$GLOBALS['mysqlI'] = new mysqli($ip, $user, $pass, $db);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_errno());
exit();
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
function dbClose(){
$GLOBALS['mysqlI']->close();
}
/////////////////////////////////////////////////////////////////////////////////////////////////
function getSQLResultSet($id){
$stmt = $GLOBALS['mysqlI']->prepare('SELECT * FROM test WHERE ID = ?');
$stmt->bind_param('i', $id);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_object()){
$ret[] = $row;
}
return $ret;
}

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.

I need to fetch some information from MySQL database and print it

I am trying to fecth some information from my MySQL database called "opskriftreg" and I want it to print it out, basically it has to retrieve 2x recipes from my database that are already created and list them accordingly with the recipes' "title" first then "description"
Here's my code, if this code is bollocks, i'd appriciate if someone could just show me a better example:
<?php
$mysqli = new mysqli ("localhost","root","","opskriftreg");
// Make a MySQL Connection
if (isset($_POST['title']) && isset($_POST['description']))
{
$username= $_POST['title'];
$password= $_POST['description'];
$query = "SELECT *
FROM opskriftreg
WHERE title = '".mysql_real_escape_string($title)."'
AND description = '".mysql_real_escape_string($description)."'";
$result = mysql_fetch_array(mysql_query($query));
# ...
}
else
{
return NULL;
}
?>
Thank you in advance :-)
EDIT:
Code changed to the following - received blank page where nothing is returned nor printed:
<?php
$mysqli = new mysqli("localhost", "root", "", "opskriftreg");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT title, description FROM opskriftreg ORDER by id DESC LIMIT 50,5";
if ($result = $mysqli->query($query)) {
/* fetch object array */
while ($row = $result->fetch_row()) {
printf ("%s (%s)\n", $row[0], $row[1]);
}
/* free result set */
$result->close();
}
/* close connection */
$mysqli->close();
?>
echo $result['column_name'];
And mysql_* functions are deprecated, use mysqli instead.
http://nl3.php.net/mysqli_real_escape_string
Try this, look for the changes I've made.
<?php
$mysqli = new mysqli("localhost", "root", "", "opskriftreg");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT title, description FROM opskriftreg ORDER by id DESC";
$statement = $mysqli->prepare($query);
$statement->execute();
$results = $statement->get_result();
while ($result = $results->fetch_assoc()) {
printf ("%s (%s)\n", $result['title'], $result['description']);
}
/* close connection */
$mysqli->close();
?>

Categories