Fetching a result from selection query in php function - php

I have a php function of selection from mySql database:
function Master_file($name, $latin ){
$HOST_DB ="localhost";
$NAME_DB="nom";
$USER_DB ="utilisaeur";
$PWD_DB="K3Pud1";
$connect = mysql_connect($HOST_DB,$USER_DB,$PWD_DB);
$db=mysql_select_db($NAME_DB);
$qry = "SELECT tax_id FROM master where name =".$name." and latin =".$latin;
echo $qry;
$result = mysql_query($qry);
while ($Res_user = mysql_fetch_assoc($result) ) {
return $Res_user['tax_id'];
}
}
an error is shown Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in /home/admin/public_html/hitlist/include/fg_membersite.php on line 446 and the line is while ($Res_user = mysql_fetch_assoc($result)
So what is the problem ? How can i fix it?

Try this
function Master_file($name, $latin ){
$dsn = 'mysql:host=localhost;dbname=nom';
$username = 'utilisaeur';
$password = 'K3Pud1';
try {
$db = new PDO($dsn, $username, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo $e->getMessage();
exit;
}
$result = $db->prepare("SELECT tax_id FROM master where name =:name");
$result->bindValue(':name', $name);
$result->execute();
foreach($result->fetchAll(PDO::FETCH_ASSOC) as $row){
echo $Res_user['tax_id'] . '<br />';
}
}
EDIT
The function above has just been updated to use PDO, display any errors, and output the tax_id value to the browser

You may try this, since your returning here return $Res_user['tax_id']; so I think you need a single row instead
function Master_file($name, $latin ){
$HOST_DB ="localhost";
$NAME_DB="nom";
$USER_DB ="utilisaeur";
$PWD_DB="K3Pud1";
$connect = mysql_connect($HOST_DB,$USER_DB,$PWD_DB);
if (!$connect) {
die("Could not connect: " . mysql_error());
}
$db=mysql_select_db($NAME_DB, $connect);
if (!$db) {
die ("Can't use " . $NAME_DB . " : " . mysql_error());
}
$qry = "SELECT tax_id FROM master where name ='" . $name . "' and latin = '" . $latin . "'";
$result = mysql_query($qry);
if( $result ){
$row = mysql_fetch_assoc($result);
return $row['tax_id'];
}
}

Related

How to get all values when parameter is null

I have a query form where I need to fetch details from a custom table in MYSQL. If the parameter is left blank all records should be fetched. If there is a value entered in the parameter then records for that value should be fetched.
This is my code so far:
<?php
$host = 'localhost';
$dbname = 'test';
$username = 'test';
$password = 'xxx';
session_start();
global $wpdb, $current_user;
$conn = mysqli_connect($host, $username, $password, $dbname);
if (!$conn) {
die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
$param_1=mysqli_real_escape_string($conn,$_GET['param_1']);
if (!empty($param_1)){
$sql = "SELECT column1 ,column2,column3,column4,column5
FROM xxx
WHERE column1='$param_1'";
} else {
$sql = 'SELECT column1 ,column2,column3,column4,column5
FROM xxx';
}
$query = mysqli_query($conn, $sql);
if (!$query) {
die ('SQL Error: ' . mysqli_error($conn));
}
?>
This works fine with one parameter. I will need to add more parameters and those could also be null.
For e.g.
$sql = "SELECT column1 ,column2,column3,column4,column5
FROM xxx
WHERE column1='$param_1' AND column2='$param_2";
Either of these could be null. How do I take care of this in MYSQL?
My question is what would be the best way to take care of this situation?
Thanks in advance.
You can keep appending the query like this:
$sql = "SELECT column1 ,column2,column3,column4,column5
FROM xxx
WHERE 1=1 ";
if(!empty($param1)){
$sql.= " and column1='$param1'";
}
if(!empty($param2)){
$sql.= " and column2='$param2'";
}
if(!empty($param3)){
$sql.= " and column3='$param3'";
}
Note: Passing parameters like this would lead to SQL injection, use binding to pass parameters to avoid SQL Injection. Here is a good read about it.
You can follow the below steps
<?php
$host = 'localhost';
$dbname = 'test';
$username = 'test';
$password = 'xxx';
session_start();
global $wpdb, $current_user;
$conn = mysqli_connect($host, $username, $password, $dbname);
if (!$conn) {
die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
$whereArr=[];
if(isset($_GET['param_1'])){
$whereArr[]="column1=" . mysqli_real_escape_string($conn,$_GET['param_1']);
}
if(isset($_GET['param_2'])){
$whereArr[]="column2=" . mysqli_real_escape_string($conn,$_GET['param_2']);
}
if(isset($_GET['param_3'])){
$whereArr[]="column3=" . mysqli_real_escape_string($conn,$_GET['param_3']);
}
$whereStr='';
if(count($whereArr)>0){
$whereStr="WHERE " . implode(" AND ",$whereArr);
}
$sql = "SELECT column1 ,column2,column3,column4,column5
FROM xxx " . $whereStr;
$query = mysqli_query($conn, $sql);
if (!$query) {
die ('SQL Error: ' . mysqli_error($conn));
}
?>
Check for each param in the above demonstrated, Put them in array.
Then check if array is isset or not, if isset create a where string and the append it to your query.
Even if no param is set your query will run without where clause.
You can do something like this for optimization of your code,
$getArr = array_filter($_GET);
// checking sql injection
$getArr = array_map(function ($v) use ($conn) {
return mysqli_real_escape_string($conn, $v);
}, $getArr);
$temp = [];
// fetching numbers for that key
foreach ($getArr as $key => $value) {
$temp[$key] = preg_replace('/[^\d]/', '', $key);
}
$str = '';
// creating condition for data fetched in get
array_walk($temp, function ($item, $key) use (&$str, $getArr) {
$str .= " column$item = '" . $getArr[$key] . "' AND ";
});
// raw query
$sql = 'SELECT column1 ,column2,column3,column4,column5 FROM xxx';
// if not empty string
if (!empty($str)) {
$sql .= rtrim($str,'AND ');
}
echo $sql;die;

Why does my PDO $stmt->bind_result() function call hang after executing a SELECT query?

I have a MySQL database with table "Test" that has one column "TestData". There are three records with the following values for TestData: "This is value 1", "Here is another string", and
"Third just for luck".
I wrote the following PHP code to retrieve the records.
<?php
try {
$hostname = "redacted";
$username = "redacted";
$password = "redacted";
$database = "redacted";
$conn = new PDO("mysql: host=$hostname; dbname=$database", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT TestData FROM Test";
$stmt = $conn->prepare($sql);
$stmt->execute();
}
catch(PDOException $e)
{
$finalResult = $finalResult . "," . $e->getMessage();
}
echo "you are here (" . $stmt->rowCount() . ")<br>";
if ($stmt->rowCount() > 0) {
echo "found (" . $stmt->rowCount() . ")<br>";
$stmt->bind_result($td);
echo "bind successful<br>";
while ($stmt->fetch()) {
echo "testdata (" . $td . ")<br>";
}
} else {
echo "nothing found<br>";
}
?>
The result I receive is
you are here (3)
found (3)
The PHP script never gets to the "echo 'bind successful'" statement. The "$stmt->bind_result($td);" statement hangs.
The query appears to work, given that rowCount = 3. I've used essentially the same structure to perform INSERTS that work properly.
What's wrong with what I'm doing? Thanks.
I changed my code to the following and it works.
<?php
$hostname = "redacted";
$username = "redacted";
$password = "redacted";
$database = "redacted";
$conn = new mysqli($hostname, $username, $password, $database);
if ($conn->connect_error) {
fwrite(STDERR, "Connection failed: " . $conn->connect_error . "\n");
exit(1);
}
$sql = "SELECT TestData FROM Test WHERE ?";
$stmt = $conn->stmt_init();
if(!$stmt->prepare($sql)) {
print "Failed to prepare statement\n";
} else {
$stmt->bind_param("s", $condition);
}
$condition = "1 = 1";
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_array(MYSQLI_NUM)) {
foreach ($row as $r) {
echo "testdata(" . $r . ")<br>";
}
}
?>
No more mixing PDO and MySQLi for me. Thanks for the help. Sorry for the inconvenience.
If you are just trying to get the items from the database using php pdo you need to store the results.
$results = $stmt->fetch(); //will get one row
$results = $stmt->fetchAll(); //will take all results and store in an array
hope this helps.

I am trying to connect to a db

I am trying to connect to a db but I keep getting an error that pops up every chance I get to change the db or connection string . I am currently using php mysqli and wamp will not show any error with the connection itself .
calc.php:
class Login {
var $con;
function __construct($con){
$this->con = $con;
}
function try_connecting(){
$connecting = true;
if($connecting){
if(!$this->con){
die ("Could not connect") . $this->con->connect_errno;
} else {
echo "connected";
}
} else {
return $connecting;
}
}
function try_login(){
if(try_connecting()){
$q = "SELECT username, password FROM persons WHERE username = " . $_POST["username"] . " AND password = " . $_POST['pwd'];
$rows = $this->con->num_rows;
if($rows == 1){
echo "true";
} else {
echo "not user";
}
}
}
}
Here is the test.php:
<?php
include("calc.php");
$u = $_POST['username'];
$p = $_POST['pwd'];
$con = mysqli_connect("localhost","root","","rdb");
$form = new Login($con);
$form->try_connecting();
$form->try_login();
?>
connection string error Unknown database
You forgot to run this query
$q = "SELECT username, password FROM persons WHERE username = " . $_POST["username"] . " AND password = " . $_POST['pwd'];
$rows = $this->con->num_rows;
Try to add
$this->con->query($q)
between the lines above

mysqli_query giving me unsolvable message

I am trying to make a basic song info page, and my only problem is the SQL. I keep getting this message:
Warning: mysqli_query() expects parameter 1 to be mysqli, string given in /var/www/tts/recommend-action.php on line 33
Here is my code:
<?php
session_start();
ini_set("display_errors",true);
ob_start();
$host = "localhost";
$user = "root";
$pass = "[MYPASSWORD]";
$db = "[MYDATABASE]";
$tb = "recommendation";
$link = mysqli_connect($host, $user, $pass, $db) or die("Failed to connect.");
$song = $_POST['song'];
$album = $_POST['album'];
$artist = $_POST['artist'];
$linkitunes = $_POST['linkitunes'];
$artwork = $_POST['albumPic'];
$song = stripslashes($song);
$album = stripslashes($album);
$artist = stripslashes($artist);
$link = stripslashes($linkitunes);
$artwork = stripslashes($artwork);
print "<br /><br /><b>User ID: </b>" . $_SESSION['user_id'] . "<br /><b>Song: </b>$song<br /><b>Album: </b>$album<br /><b>Artist: </b>$artist<br /><br />";
$sql = "INSERT INTO recommendation (user_id, artist, song, album, artwork, linkitunes) VALUES (" . $_SESSION['user_id'] . ", $artist, $song, $album, $artwork, $linkitunes);";
$postrec = mysqli_query($link, $sql);
if ($postrec == true) {
print "sucess";
}
else {
print "<br /><br />failed";
}
ob_flush();
?>
I cannot find a solution. Help is very greatly appreciated.
You connect fine and $link is good:
$link = mysqli_connect($host, $user, $pass, $db) or die("Failed to connect.");
But then later redefine as a string:
$link = stripslashes($linkitunes);
And then you try and use the string:
$postrec = mysqli_query($link, $sql);

Help with IF THEN breaking when comparing results from MYSQL query

I'm have a problem with an invite system. The if statement seems to break. It shows the message "Fail" but the UPDATE statement still executes. Why do both the THEN and the ELSE excute?
$dbConn = new dbConn();
// Check if POST user_username and user_hash are matching and valid; both are hidden for fields
$sql = "SELECT user_username "
. "FROM table_users "
. "WHERE user_id=".mysql_real_escape_string($_POST["user_id"])." "
. "AND user_hash='".mysql_real_escape_string($_POST["user_hash"])."' "
. "AND user_enabled=0;";
$objUser = $dbConn->query($sql);
// If result contains 1 or more rows
if( mysql_num_rows($objUser) != NULL ){
$objUser = mysql_fetch_assoc($objUser);
$ssnUser->login( $objUser["user_username"] );
$sql = "UPDATE table_users SET "
. "user_enabled=1, "
. "user_first_name='".mysql_real_escape_string($_POST["user_first_name"])."', "
. "user_last_name='".mysql_real_escape_string($_POST["user_last_name"])."', "
. "user_password='".mysql_real_escape_string( md5($_POST["user_password"]) )."' "
. "WHERE user_id=".mysql_real_escape_string($_POST["user_id"]).";";
$dbConn->query($sql);
echo "Success";
header( "Refresh: 5; url=/account/?action=domains" );
} else {
echo "Fail";
}
This dbConn Class is as follows:
class dbConn{
var $username = "xxxx_admin";
var $password = "xxxxxxxx";
var $server = "localhost";
var $database = "xxxx";
var $objConn;
function __construct(){
$conn = mysql_connect( $this->server, $this->username, $this->password, true );
if( !$conn ){
die("Could not connect: ".mysql_error() );
} else {
$this->objConn = $conn;
}
unset($conn);
}
function __destruct(){
mysql_close( $this->objConn );
unset( $this );
}
function query( $query, $db = false ){
mysql_select_db( $db != false ? $db : $this->database, $this->objConn );
$result = mysql_query( $query );
unset($query,$db);
return $result;
}
}
I don't see anything really weird in your code. Could there be a "Fail" call in your login() method? Either way, I would change the line:
if( mysql_num_rows($objUser) != NULL ){
to:
$rowCount = mysql_num_rows($objUser);
if($rowCount and $rowCount > 0){
And, put an exit(); call after your header() line.

Categories