Variable inside curly brackets - php

I know how to execute php variable inside quotes
$q1 = 1;
$q2 = 2;
$q3 = 3;
$q4 = 4;
$q5 = 5;
echo "${q1}"; //outputs 1
How can i output them in a loop?
for($i=1; $i<=5; $i++)
{
echo "${q$i}"; //how to make $i work here?
}
How to make $i work along with $q?
UPDATE
i want the quotes to be there, because i am creating a string in a loop and i want to pass that loop to mysql query. So i want the string to be like
$str = '$q1, $q2, $q3';
and when i pass it to mysql query it should interpret the values of $q1, $q2, $q3 which is 1,2,3
mysql_query("INSERT INTO users (col1, col2, col3) VALUES ($str)");
So it should become
mysql_query("INSERT INTO users (col1, col2, col3) VALUES (1,2,3)");
It is just an example i know the syntax of mysql_query is wrong but you know

I think what you are looking for is this:
<?php
$arr = array();
$q1 = 1;
$q2 = 2;
$q3 = 3;
$q4 = 4;
$q5 = 5;
for($i=1; $i<=5; $i++)
{
$arr[] = ${"q".$i};
}
$str = implode($arr, ',');
print_r($str);
Outputs:
1,2,3,4,5
In action: http://codepad.org/ep7sraT5

for($i=1; $i<=5; $i++)
{
$x = "q$i";
echo $$x;
}
works!

Use this code, it should work :)
echo ${"q${i}"};

The double quotes around the whole thing are useless
use
echo ${'q' . $i};
EDIT: If you want to create the comma seperated string, why not try
$q1 = 1;
$q2 = 2;
$q3 = 3;
$q4 = 4;
$q5 = 5;
$parts = array();
for($i=1; $i<=5; $i++)
{
$parts[] = ${'q' . $i};
}
$str = implode(', ', $parts);
Also consider escaping the values before running the MYSQL, you could do this within the for loop before adding the value to the $parts array

for($i=1; $i<=5; $i++)
{
echo ${"q".$i};
}
Output:
12345
Codepad: http://codepad.org/2PIshh41
UPDATE:
Since you wanted to store the value in varible, you can do this:
$str = '';
for($i=1; $i<=5; $i++)
{
$str .= "${"q".$i}, ";
}
$str = rtrim($str, ' ,'); //trim last comma
mysql_query("INSERT INTO users (col1, col2, col3) VALUES ($str)");
//becomes mysql_query("INSERT INTO users (col1, col2, col3) VALUES (1, 2, 3, 4, 5)")
Hope this helps!

Related

PHP explode and sort

I need to sort an exploded string to write into database.
With the code down below it works, but I was not able to detect the summary of arrays outside the foreach loop.
So $terms[0].$terms[1].$terms[2] was not correct.
Cause as example $terms[0].$terms[1].$terms[2].$terms[3] was required for 4 terms in string.
How could that be solved?
$terms = explode(";", "banana;apple;lemon");
sort($terms);
$length = count($terms);
for($x = 0; $x < $length; $x++) {
$terms[$x] = $terms[$x].'; ';
}
$sorted_terms = $terms[0].$terms[1].$terms[2]; // <<< should changed dynamically
$sql = mysqli_query($dbcon,"INSERT INTO mydatabase (terms) VALUES ('$sorted_terms')");
Use PHP implode which is an exact opposite of explode and intended for just this sort of thing.
$terms = explode(";", "banana;apple;lemon");
sort($terms);
$sorted_terms = implode(";", $terms);
//$sorted_terms = "apple;banana;lemon";
Edit:
As you're using procedural MySQLi for your data entry you should also use mysqli_real_escape_string to limit SQL injection into your database. I know it may not apply to your current work but it's best practise to get into - short of actually using Prepared Statements.
so:
$sql = mysqli_query($dbcon,"INSERT INTO mydatabase (terms)
VALUES ('".mysqli_real_escape_string($dbcon, $sorted_terms)."')");
Using Prepared Statements instead is very highly recommended.
Simply use string concatenation.
Use $terms1 as string in for loop.
$terms1 = "";
$terms = explode(";", "banana;apple;lemon");
sort($terms);
$length = count($terms);
for($x = 0; $x < $length; $x++) {
$terms1 .= $terms[$x].'; ';
}
//$sorted_terms = $terms[0].$terms[1].$terms[2];
//$sql = mysqli_query($dbcon,"INSERT INTO mydatabase (terms) VALUES ('$sorted_terms')");
$sql = mysqli_query($dbcon,"INSERT INTO mydatabase (terms) VALUES ('$terms1')");
Try $sorted_terms = implode(';', $terms);
http://php.net/manual/en/function.implode.php

PHP Variable printing multiple variables

I have several variables, for example:
$q1
$q2
$q3
...
$q50
I would like to combine them info one variable who puts them info the VALUE of an INSERT INTO. Maybe a for loop?
INSERT INTO $table_name ($column_names) VALUES($q1, $q2, $q3)
So it might look like this
INSERT INTO $table_name ($column_names) VALUES($combined_variables)
This way, i could just manually add another variable to the $q51 and it would populate VALUE automaticly.
Is this possible? Maybe somehing like this (but this does not work)
$combined_variables = '';
for( $i = 1; $i <= 50 $i++ ) {
$combined_variables .= 'q' . $i . ', ';
}
$combined_variables = substr($combined_variables, 0, -2); //minus 2 to remove the last space and comma
This should work for you:
(Here I start with $q1 and assign it to the array until the next $qX is not set)
<?php
$combined_variables = [];
$count = 1;
while(isset(${"q" . $count})){
$combined_variables[] = ${"q" . $count};
$count++;
}
?>
So as an example:
$q1 = 5;
$q2 = 2;
You would end up with following array:
Array ( [0] => 5 [1] => 2 )
And then you can simply use it in the query like this:
"INSERT INTO $table_name ($column_names) VALUES(" . "'" . implode("','", $combined_variables) . "'" . ")"
You can use variable variables like this:
$combined_variables = array();
for ($i = 1; $i <= 50 $i++) {
$var = 'q' . $i;
$combined_variables[] = ${$var};
}
$combined_variables = implode(', ', $combined_variables);
However, if you can use an array instead of 50 variables you'd have a much easier job.

To prevent sql-injection, is it sufficient for mysqli_real_escape_string() to be applied only once to a comma separated string?

I apologize if someone posted this and I missed it...I googled and scanned SO for a similar question and if it exists, I missed it.
Scenario: user enters comma separated input. The string needs to be exploded and each piece used to update different table row. Is it sufficient to apply mysqli_real_escape_string() once:
<?php include 'connect.php';
$ExplodedCommaString = explode(",", mysqli_real_escape_string($cxn, $_GET['userinput']));
$Count = count($ExplodedCommaString);
for ($i = 0; $i < $Count; $i++) {
$myID = $ExplodedCommaString[$i];
$sql = mysqli_query($cxn, "UPDATE myTable SET myValue = 'y' WHERE id = '$myID'");
}
?>
or must each pass through the for loop apply mysqli_real_escape_string?
<?php include 'connect.php';
$ExplodedCommaString = explode(",", $_GET['userinput']);
$Count = count($ExplodedCommaString);
for ($i = 0; $i < $Count; $i++) {
$myID = $ExplodedCommaString[$i];
$sql = mysqli_query($cxn, "UPDATE myTable SET myValue = 'y' WHERE id = '".mysqli_real_escape_string($cxn, $myID)."'");
}
?>
So, apply it once on the comma-separated string and explode the string, or explode the string and then apply it for each iteration of the for loop?
By using prepared statements you don't have to worry about escaping the content yourself, or how to properly do it.
Example:
<?php include 'connect.php';
$ExplodedCommaString = explode(",", $_GET['userinput']);
$Count = count($ExplodedCommaString);
for ($i = 0; $i < $Count; $i++) {
$myID = $ExplodedCommaString[$i];
// replace your raw var with ? in the sql statement
$sql = "UPDATE myTable SET myValue = 'y' WHERE id = ?";
// run the prepare method
$stmt = $conn->prepare($sql);
// bind the '?' in the sql statement to $myID of type int
// I'm assuming it's an int here, if it's a string change the 'i' to an 's'
$stmt->bind_param('i', $myID);
// and run it
$stmt->execute();
}
?>
Some further reading, examples, and discussion.

Insert multiple rows using single query

I want to insert multipl rows in single query.
$firstname = array('Arfan','Awais','Ahmad'.....);
$lastname = array('Haider','k','Raza'..........);
Insert Data:
INSERT INTO `table_nmae`(firstname,lastname)
VALUES
('Arfan','Haider'),('Awais','k'),('Ahmad','Raza');
I can do it very easily if these are only three record.
If I did not know how many records are present then I can not able to use the above.
Then what I did do?
UPDATE:
If I can not know the numbers of record in array.I can simply use foreach loop to do this
But this decrease the performance.
foreach($firstname as $f){
foreach($lastname as $l){
INSERT INTO `table_name`(firstname,lastname)
VALUES('$f','$l');
}
}
Now this time I am using multi query.I think single query is good to performance.
FOR ONE COLUMN:
If I had only one column it is very easy to use single query for this.
INSERT INTO `table_name`(firstname) VALUES
.implode(',', $firstname);
But here is multi column how can I do that for those.
Thanks.....
Use for loop if $firstname and $lastname array are of same length
$str = "INSERT INTO `table_nmae`(firstname,lastname) VALUES"; // create string of query
for($i = 0 ;$i< count($firstname); $i++) {
$str .= "('" . $firstname[$i] . "','" . $lastname[$i] . "'),"; //append the values
}
$str = trim($str, ","); // remove last ,
Try
$size_of_array = count( $firstname );
$query = "INSERT INTO `table_nmae`(firstname,lastname) VALUES ";
for($i = 0; $i < $size_of_array; $i++ )
{
if( $i !== ($size_of_array-1))
$query .= "('{$firstname[$i]}', '{$lastname[$i]}'),";
else
$query .= "('{$firstname[$i]}', '{$lastname[$i]}')";
}
echo $query;
?>
Suppose you have array of values e.g. $values_arr.
$count = count( $values_arr );
$query = "INSERT INTO `table_nmae`(firstname,lastname) VALUES ";
for($i = 0; $i < $count; $i++ )
{
if( $i == 0)
$query .= "('{$values_arr[$i]['firstname']}', '{$values_arr[$i]['lastname']}')";
else
$query .= ",('{$values_arr[$i]['firstname']}', '{$values_arr[$i]['lastname']}')";
}
echo $query;

Array output or json output without quotes

How i can output my array without quotes on this situation
for($i=1; $i <= date("d"); $i++) { $days[] = $i; }
echo json_encode($days); // ouput [1,2,3,4,5,6,7,8,9,10]
This first on is fine, but on the second one
for($i=1;$i <= date("d"); $i++) {
$Sql = "SELECT COUNT(Stats_Clicks) AS Total FROM tabstats WHERE DAY(Stats_Date) = $i
AND MONTH(Stats_Date) = $month
AND YEAR(Stats_Date) = $year
";
$Query = mysql_query($Sql,$Conn) or die (mysql_error($Conn));
$Rs = mysql_fetch_array($Query);
$clicks[] = $Rs['Total'];
}
echo json_encode($clicks);
json output returns this
["1","1","0","0","0","0","0","0","0","0","0"]
i need this without quotes on this format.
You just need cast to integer.
$clicks[] = (int)$Rs['Total'];
Untested:
$clicks[] = (int) $Rs['Total'];
try array_map with intval function
like this:
echo json_encode(array_map("intval",($Rs['Total'])));
example:
print_r(json_encode(array_map("intval",array("1","2","3"))));
=> [1,2,3]

Categories