0

The SQL query is good but the following code doesn't return any value. I need to display just single value from the query.

$clientId=$row["clientid"];
        $sql2="select cname from Clients where clientid='$clientId'";
        //$result = $conn->query($sql2);
        $result = mysql_query($sql2);
        echo $result;
3
  • 1
    What happens if $clientId is 5'; drop table Clients; -- ? Commented Jan 25, 2015 at 7:31
  • Don't use mysql*-functions they are depricated. Commented Jan 25, 2015 at 7:31
  • Thanks bish for the info Commented Jan 27, 2015 at 0:10

5 Answers 5

1

This is how you should do it using mysqli

$query = 'SELECT cname FROM Clients WHERE clientid = ?';

if($stmt = $mysqli->prepare($query)){
    $stmt->bind_param('i', $_POST['clientid']);
    $stmt->execute();
    $stmt->bind_result($cname);
    $stmt->fetch();

    echo $cname; // (optional, prints it out)
}
Sign up to request clarification or add additional context in comments.

Comments

0
$clientId=$row["clientid"];
        $sql2="select cname from Clients where clientid='$clientId'";
        //$result = $conn->query($sql2);
        $result = mysql_query($sql2);
        foreach($result->result() as $row){
         echo $row->cname;
}

Comments

0

In order to use the result you need to fetch from it. E.g.:

$result = mysql_query($sql2);
$row = mysql_fetch_array($result);
$cname = $row[0];

Comments

0

mysql deprecated

You are applying wrong methods.

Your code should look like :

<?php
$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);
    ?> 

Also ready more >> http://www.w3schools.com/php/func_mysqli_fetch_array.asp

Comments

0

Try this way and fix the typo on your sql query use (`) mark for column names, but first see documentation for this deprecated API, instead use PDO or MYSQLi.see mysql_query

$clientId=$row["clientid"];
$sql2="select `cname` from Clients where clientid='$clientId'";
$result = mysql_query($sql2);
$row = mysql_fetch_assoc($result);
//use column name,as you fetch result as associative array
$canme = $row['cname']; 
echo $canme;

N.B: Use PDO or MYSQLi, for prepared statement that will fix your SQL INJECTION related Problems

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.