PHP Variable in Select Statement - php

I've written this PHP-Script which is working, and now I want to change the row name into a variable to (not sure if row is correct), I mean the "name" from the select name...
I've tried nearly everything, but nothing gave me the right result.
I know that the normal thing how I can use variables in a statement like ("'. $var .'") won't work.
<?php
require_once 'config.php';
$id = $_GET["id"]; //ID OF THE CURRENT CONTACT
$user = $_GET["user"]; //ID OF THE CURRENT USERS
$query = mysql_query("SELECT name FROM contacts WHERE contact_id='". mysql_real_escape_string( $id ) ."' and user_id='1';");
$retval = mysql_fetch_object($query)->name;
$retval = trim($retval);
echo $retval;
?>

This is much easier isn't it?
$sql_insert =
"INSERT INTO customers (
`name`,
`address`,
`email`,
`phone`
)
VALUES (
'$name',
'$address',
'$email',
'$phone'
)";

Is it this you're looking for? Even your question in German isn't that clear to me :
$field = 'name';
$query = mysql_query("SELECT $field FROM contacts WHERE contact_id='". mysql_real_escape_string( $id ) ."' and user_id='1';");
$retval = mysql_fetch_object($query)->$field;

You can usi it something like this. Currently i assume you get only one row back and want to use only one field.
<?php
require_once 'config.php';
$id = $_GET["id"]; //ID DES DERZEITIGEN KONTAKTES
$user = $_GET["user"]; //ID DES DERZEITIGEN USERS
//Use variable inside closures `` and just in case escape it, depends how you get variable
$query = mysql_query("SELECT `".mysql_real_escape_string($variable)."` FROM contacts WHERE contact_id='". mysql_real_escape_string( $id ) ."' and user_id='1';");
if (!$query) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($query); //Retriev first row, with multiple rows use mysql_fetch_assoc
$retval = $row['0']; //Retriev first field
$retval = trim($retval);
echo $retval;
?>

Please post in English. Everyone else does.
Try using a different fetch method - fetch an associative array, then use the dynamic parameter to retrieve whatever column it is you need.
Have you considered using PDO?

I believe you are confusing matters (unintentionally) due to your use of the word 'row'. Judging by your example you mean field/column. It sounds like you wish to specify the fields to select using a variable which can be done by any of these methods...
$fields = "name, age";
$sql = "SELECT $fields FROM table";
$sql = "SELECT {$fields} FROM table";
$sql = "SELECT ".$fields." FROM table";
NB it is important that you have secure date in the $fields element, I would suggest using a whitelist of allowed values i.e.
// assuming $_POST['fields'] looks something like array('name','age','hack');
$allowed = array('name', 'age');
$fields = array();
foreach ($_POST['fields'] as $field) {
if (in_array($field, $allowed)) {
$fields[] = $field;
}
$fields = implode(', ', $fields);

Wouldn't this work?
$result = mysql_fetch_array($query);
echo trim($result['name']);

You should never put a variable into field list.
If want a variable field name, select *
and then use your variable to fetch particular field
<?php
require_once 'config.php';
$id = mysql_real_escape_string($_GET["id"]); //ID DES DERZEITIGEN KONTAKTES
$user = $_GET["user"]; //ID DES DERZEITIGEN USERS
$query = "SELECT * FROM contacts WHERE contact_id='$id' and user_id='1'";
$result = mysql_query($query) or trigger_error(mysql_error().$query);
$row = mysql_fetch_array($result);
//and finally
$fieldname = "name";
$retval = $row[$fieldname];
echo $retval;
?>

Related

How to select rows from array of keys?

I have a table and the primary key is 'unique_identifier'. I would like to select the rows from a number of keys. I have an array that contains the keys who's data from the table I would like to select and retrieve all at once. Please set aside security concerns.
$myArray = array('GMVC0001', 'GMVC0002', 'GMVC0003', 'GMVC0004', 'GMVC0005');
$sql = "SELECT * FROM tracker WHERE unique_identifier='????????????";
$result = $mysqli -> query($sql);
$count = $result -> num_rows;
if($count > 0){
echo 'count: '.$count;
}else{
echo 'error';
}
You can use implode function of PHP and IN operator of SQL.
$myArray = array('GMVC0001', 'GMVC0002', 'GMVC0003', 'GMVC0004', 'GMVC0005');
$sql = "SELECT * FROM tracker WHERE unique_identifier in ('" . implode("','", $myArray) ."')";
Suppose you have name, roll, email in a table.After completing your sql that you have done you can access every attribute by this way.
while($row = $result->fetch_assoc()){
$name = $row["name"];
$email = $row["email"];
$roll = $row["roll"];
}

Need Some Help Regarding Fetching Data from Mysql using explode function

In the below script I want to fetch data from mysql using a explode function and also a variable within an explode function.
Here's how I want to get
<?php
include ('config.php');
$track = "1,2,3";
$i = 1
$trackcount = explode(",",$track);
$sql = "SELECT * FROM tracks WHERE id='$trackcount['$i']'";
$retval = mysql_query($sql, $conn);
while ($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "{$row['track_name']}";
}
mysql_free_result($retval);
?>
This is the code
$sql = "SELECT * FROM tracks WHERE id='$trackcount[$i]'";
I want sql to fetch data from tracks table where id = $trackcount[$i]
Whatever the value of $trackcount[$i] mysql should fetch but it shows a blank screen.
If I put this
$sql = "SELECT * FROM tracks WHERE id='$trackcount[1]'";
It works perfectly
save your $trackcount[$i] in one variable and then pass it in the query as given below
<?php
include ('config.php');
$track = "1,2,3";
$i = 1;
$trackcount = explode(",",$track);
$id=$trackcount[$i];
$sql = "SELECT * FROM tracks WHERE id='$id'";
$retval = mysql_query($sql, $conn);
while ($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "{$row['track_name']}";
}
mysql_free_result($retval);
?>
and one more thing check your previous code with echo of your query and see what is passing ok.
echo $sql = "SELECT * FROM tracks WHERE id='$trackcount['$i']'";//like this
problem is with your query
$sql = "SELECT * FROM tracks WHERE id='$trackcount['$i']'";//change
to
$sql = "SELECT * FROM tracks WHERE id='$trackcount[$i]'";
Generally you would want to use the IN operator with this type of query, so for you this would be:-
$sql="SELECT * FROM `tracks` WHERE `id` in (".$track.");";
or, if the $ids are in an array,
$sql="SELECT * FROM `tracks` WHERE `id` in (".implode( ',', $array ) .");";

MYSQL query using a set of values (values stored from a session array) not working

I'm just a beginner and I'm doing a project (a shopping cart). User can add a product to the cart and the id of the product stores in a session. When I use those ids to echo out PRICE from DB it's not working. I'm using PHP & MYSQL. Here is my code
if(count($_SESSION['cart_items'])>0){
// getting the product ids
$nos = "";
foreach($_SESSION['cart_items'] as $no=>$value){
$nos = $nos . $no . ",";
}
// removing the last comma
$nos = rtrim($nos, ',');
//echo $nos; (will display like this INT VALUES 1,2,3,4)
$nos=mysql_real_escape_string($nos);
$site4->DBlogin();
$qry = "SELECT * FROM vendorproducts WHERE product_no IN('.implode(',',$nos).')";
$result = mysql_query($qry);
$row = mysql_fetch_assoc($result);
echo $row['price'];
}
PHP is not recursively embeddable:
$qry = "SELECT * FROM vendorproducts WHERE product_no IN('.implode(',',$nos).')";
^---start of string end of string ---^
Since you're already in a string, .implode(...) is just plain text, NOT executable code.
This means your query is illegal/invalid SQL, and if you had even basic/minimal error checking, would have been told about this:
$result = mysql_query($qry) or die(mysql_error());
^^^^^^^^^^^^^^^^^^^^^^
I have fixed the issue and thanx MARC for your suggestions.
I was making two mistakes:- IMPLODE input field was not an array. and as Marc said the query was not executable.
Changes made :-
$nos = rtrim($nos, ',');
**$narray = array($nos);**
$fgmembersite4->DBlogin();
$qry = **'SELECT * FROM vendorproducts WHERE product_no IN ('.implode(',',$narray).')'**;
$result = mysql_query($qry) or die(mysql_error());
**while (**$row = mysql_fetch_assoc($result)){
echo $row['price'];}

Trouble when passing a php variable as an argument in mysql query

I'm trying to use a php variable as a search term when querying a mysql database, first I get the variables from the HTML form:
<?php
//Create variables
$vals = array($_POST["id_number"], $_POST["id_name"], $_POST["id_submitname"]);
$keys = array('idno_1', 'name_2', 'subname_3');
//combine keys to arrays
$var = array_combine($keys, $vals);
//santise variables
$variables = filter_var_array($var, FILTER_SANITIZE_STRING);
$idno = $variables['idno_1'];
$name = $variables['name_2'];
$subname = $variables['subname_3'];
After connecting to the database I run the query:
//Select entry from table and display
if (!$idno == '')
{
$sql = "SELECT * FROM `healthsafety` WHERE ID = '$idno'";
$result = mysqli_query($connection, $sql);
}
elseif (!$name == '')
{
$result = mysqli_query($connection, "SELECT * FROM `healthsafety` WHERE LOWER (nameinvolved) = LOWER ('$name')");
}
else
{
$result = mysqli_query($connection, "SELECT * FROM `healthsafety` WHERE LOWER (submitbyname) = LOWER ('$subname')");
}
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
It is not returning anything from the db, when I select * FROM without trying to use the variable as a search it displays all entries ok, am I making an error when passing the variable to the query? I've tried different combinations of quotes, back ticks and using other variables for the query. Any help would be greatly appreciated!
LOWER is a function and the arguments needs to be wrapped in parentheses.
Your query should look like:
$result = mysqli_query($connection, "SELECT * FROM `healthsafety`
WHERE LOWER(nameinvolved) = LOWER('$name')");
For easier debugging, I'd first print out the query:
$query = "SELECT * FROM `healthsafety`
WHERE LOWER(nameinvolved) = LOWER('$name')";
echo $result;
... and then run it manually using the MySQL Interactive shell or using web interfaces like phpMyAdmin. That could help you isolate the issue further and then figure out what's wrong.
First you needed to be sure that all data are correct. then Try this:
if (isset($idno) && !$idno == '')
{
$sql = "SELECT * FROM `healthsafety` WHERE ID = $idno";
$result = mysqli_query($connection, $sql);
}
else if (isset($name) && !$name == '')
{
$result = mysqli_query($connection, "SELECT * FROM `healthsafety` WHERE LOWER (nameinvolved) = LOWER ('$name')");
}
else
{
$result = mysqli_query($connection, "SELECT * FROM `healthsafety` WHERE LOWER (submitbyname) = LOWER ('$subname')");
}
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);

Created a new variable by pulling a value from a MySQL table

I am using a page where a variable $submissionid is being posted to it. I would like to use this variable and pull the field subcheck from a MySQL table called submission. I would like the value of the field subcheck to simply be a new variable $subcheck. I'm not sure how to do this. I have a query below, but how to I convert the result of the query below into a variable called $subcheck? (For any given submissionid, there will only be one $subcheck.)
Thanks in advance,
John
$querysub = mysql_query("SELECT subcheck FROM submission WHERE submissionid = '$submissionid' ");
mysql_query($querysub) or die(mysql_error());
You can try:
$querysub = mysql_query("SELECT subcheck FROM submission WHERE submissionid = ".
mysql_real_escape_string($submissionid));
$result = mysql_query($querysub);
if (!$result) {
die 'Could not run query: ' . mysql_error();
}
$subcheck = mysql_result($result, 0);
This is more of a 'php' question, than it is for mysql.
Look up the 'extract' keyword for PHP Link. Effectively 'extract' takes the contents of an associative array and creates php variables (symbol table entries) using the names of keys. Each php variable will then contain the associated value.
You should be able to just:
$result = mysql_query("SELECT * FROM table");
$row = mysql_fetch_array( $result, MYSQL_ASSOC );
extract( $row ); // Create php variables, named after each column in the table.
$row["field"] == $field; // Will be a true statement after 'extract()'
Enjoy, you now have the ability to have your code dynamic adjust to a DB schema that could be changed.
-- J Jorgenson --
This should work:
$querysub = mysql_query("SELECT subcheck FROM submission WHERE submissionid = '" . $submissionid ."' ");
$result = mysql_query($querysub) or die(mysql_error());
$row = mysql_fetch_assoc( $result );
if ($row ) {
$subcheck = $row['subcheck'];
} else {
echo "Subcheck not found";
}
Be careful with the escape characters around $submissionid in your query string. In your sample, they are probably letting the name of the variable go into the string you send to the mysql server.

Categories