I am just a beginner in php. I used the following code to display the user names fetched from the database.
$select_tl = "SELECT `varTeamleader` FROM `tbl_team` WHERE `intTeamid` = '" . $id . "'";
$select_tl_res = mysql_query($select_tl);
$select_tl_num = mysql_num_rows($select_tl_res);
if ($select_tl_num > 0) {
$fetch_tl = mysql_fetch_array($select_tl_res);
$tl = $fetch_tl['varTeamleader'];
$sep_tl = explode(",", $tl);
foreach ($sep_tl as $key => $value) {
$sel_tlname = "SELECT * FROM `tbl_user` WHERE `intUserid` = '" . $value . "'";
$sel_tlname_res = mysql_query($sel_tlname);
$sel_tlname_num = mysql_num_rows($sel_tlname_res);
if ($sel_tlname_num > 0) {
$fetch_username = mysql_fetch_array($sel_tlname_res);
$user_name = $fetch_username['varName'];
echo $user_name . ", ";
}
}
}
I need to echo the user_name with comma after every value but not after last one. How can i do that?
Add the items to an array and then implode(',', $arr).
After you're done iterating, remove the last comma. That's an easy way of doing it.
$user_name=substr($user_name,0,-2)
Related
I'm trying to loop through every row in a table, and remove 5 characters from the end of one column. I have written the following code but it seems to remove 2 characters for some reason.
<?php
$connection = new mysqli('localhost', 'nawd_test', 'password', 'nawd_test');
if ($connection->connect_errno > 0) {
die ('Unable to connect to database [' . $connection->connect_error . ']');
}
$sql = "SELECT *
FROM test";
if (!$result = $connection->query($sql)) {
die ('There was an error running query[' . $connection->error . ']');
}
//Create an array to hold the values of id's already changed
$ids = [];
$newVals = [];
echo '<p>Fetching rows...</p>';
while ($row = $result->fetch_assoc()) {
//Check / Add the id
if (in_array($row['id'], $ids)) {
echo '<p style="red"><strong>Error: Script has repeated itself!</strong></p>';
break;
}
$ids[] = $row['id'];
$rowName = $row['name'];
$newName = substr($rowName, -1);
$newName = rtrim($rowName,$newName);
$newVals[] = $newName;
}
//Now loop and update
$newValID = 0;
foreach ($ids as &$id) {
echo '<p>Updating row with ID ' . $id . '</p>';
mysqli_query($connection, "UPDATE test SET name ='" . $newVals[$newValID] . "' WHERE id=" . $id);
echo '<p>Column successfully changed "<em>' . $newVals[$newValID] . '</em>"</p>';
$newValID++;
}
echo '<p style="color: green;"><strong>Script complete!</strong></p>';
?>
Dont do this in php, you can do it with a single sql query:
UPDATE test SET name = LEFT(name, LENGTH(name) - 5)
Change
$newName = substr($rowName, -1);
$newName = rtrim($rowName,$newName);
into
$newName = substr($rowName, 0, strlen($rowName) - 5);
With the way you're working, you could never predict how many characters that would have removed at the end.
Minimum 1, maximum the whole word.
Please read the documentation about rtrim and substr.
try this if you wanna doit inside the query:
update table1 set name=substr(name,-5,length(name))
My Stored Procedure only works on the first iteration. My code:
// Display Event
$result = mysql_query("select ....",$connection_mercury);
while($row = mysql_fetch_array($result))
{
$id = $row['id'];
$provider = $row['name'];
$details = mysql_query("CALL $my_schema_to_use.getRefId($provider);",$connection);
while($b_row = mysql_fetch_array($details))
{
$details_result = $b_row['age'] . " - " . $b_row['address'];
}
echo "<td>$details_result</td><td>$id</td>
}
Lets say the outer while loop does 2 loops as expected. But the 'CALL' only returns a value on the first loop every time. The $details variable always remains empty for any loop after the first one.
$details_result varible are overwritting with inner loop.
while($b_row = mysql_fetch_array($details))
{
$details_result = $b_row['age'] . " - " . $b_row['address'];
}
Code should be
while($b_row = mysql_fetch_array($details))
{
$details_result[] = $b_row['age'] . " - " . $b_row['address'];
}
I'm not too familiar with PHP arrays, I have the following code that generates query to output the results needed.
$allstore = $_POST['store'];
function createSelect($allstore)
{
if (empty($allstore))
return "";
$querySelect = "";
$queryJoin = "";
$baseTable = "";
foreach ($allstore as $store => $value) {
if (!$querySelect) {
$baseTable = $store;
$querySelect = "SELECT " . $store . ".item_no, " . $store . ".actual_price, " . $store . ".selling_price, " . $store . ".qty as " . $store;
} else {
$querySelect .= ", " . $store . ".qty as " . $store;
$queryJoin .= "
INNER JOIN " . $store . " ON " . $baseTable . ".item_no = " . $store . ".item_no";
}
}
$querySelect .= " FROM " . $baseTable;
$query = $querySelect . $queryJoin;
return $query;
}
//Stores to be shown
$allstore = ['s_M9' =>0 , 's_M10' =>1];
$query = (createSelect($allstore));
$result = mysql_query($query);
//rest of code...
As you can see above, at the very top there is $allstore = $_POST['store']; Which collects values based from previous form POST method that has checkbox with the name=store[] .
Now According to the function shown, if I create my own keys and values like this
$allstore = ['s_M9' =>0 , 's_M10' =>1];
the output shows exactly what i'm looking for. But the problem goes on how to let $allstore implode those stores s_M9, s_M10 based on what the user has selected on the previous page ( checkbox )? I mean, the user can select either one of the stores or Both stores . How can I implode the checked results between those brackets without inserting them manually?
Thank You
Edit :
<?php
echo "<form action='somewhere.php' method='POST'>";
$query = "SELECT * from stores_list ORDER BY short Asc";
$result = mysql_query($query);
if(mysql_num_rows($result)>0){
$num = mysql_num_rows($result);
for($i=0;$i<$num;$i++){
$row = mysql_fetch_assoc($result);
echo "<input type=checkbox name=store[] value={$row['short']} style='width:20px; height:20px;'>{$row['short']}";
}
}
else{
//No Stores Available
echo "No Stores Found !";
}
echo "</td><input type='submit' value='Search'/></form>";
$allstore = [];
if (!empty($_POST['store'])) {
foreach ($_POST['store'] as $value) {
$allstore[$value] = 1; // or 0, it doesn't matter because your function adds all the keys
}
}
$query = (createSelect($allstore));
$result = mysql_query($query);
And of course you have to take care of your createSelect function to avoid SQL Injections, please read here
Following PHP code is working fine when only ONE set of array values in POST ie, on index value 0...When index value is greater than one, duplicate entries are getting inserted into the table..please help...
$sql = "INSERT INTO js (s_name, s_age, s_marks, s_school) VALUES ";
foreach($_POST as $objResult)
{
$i = 0;
foreach($objResult as $Result){
$i++;
if($i>1)// add ',' after first set of values in INSERT..
{
$sql .= ",";
}
$name = $Result['sname'];
$age = $Result['age'];
$mark = $Result['mark'];
$school = $Result['school'];
$sql .= "('".$name."','" .$age."','".$mark."','" .$school."')";
$result=$conn->query($sql);
}}
You can completely eliminate any issues with all of that iterating you have going on by doing something like this:
foreach($_POST as $objResult) {
foreach($objResult as $Result) {
$sql .= "(" . implode(', ', $Result) . "),";
}
}
$result=$conn->query($sql);
And now do you notice how I moved the query out of your loops? That makes sure that you run it properly and not on every iteration (loop) of the data.
Here is a working Example (You will have to press ctrl + enter to run the code)
You need to move the
$result=$conn->query($sql);
out of the inner loop, you are not clearing the string, so it will keep adding in the entries added already.
Thank you for your suggessions. And I changed my code as following..
$sql = "INSERT INTO js (s_name, s_age, s_marks, s_school) VALUES ";
foreach($_POST['student'] as $Result)
{
$name = $Result['sname'];
$age = $Result['age'];
$mark = $Result['mark'];
$school = $Result['school'];
$sql .= "('".$name."','" .$age."','".$mark."','" .$school."'),";
}
$sql = rtrim($sql,",");
$result=$conn->query($sql);
you can change code like this
foreach($_POST as $objResult) {
foreach($objResult as $Result) {
$sql .= "(" . implode(', ', $Result) . "),";
}
}
$result=$conn->query($sql);
Let's say i have and array like this
$array= Array('id'=>'3', 'name'=>'NAME', 'age'=>'12');
Keys from this array are name of columns in table and values are value of columns which i need to update.
I want to update the table based on keys and values.
I am using ADODB
Please help me
try this:
$sql = "UPDATE table SET ";
foreach($array as $key=>$value) {
$sql .= $key . " = " . $value . ", ";
}
$sql = trim($sql, ' '); // first trim last space
$sql = trim($sql, ','); // then trim trailing and prefixing commas
and of course the WHERE clause:
$sql .= " WHERE condition = value";
you will get the string:
UPDATE table SET id = 3, name = NAME, age = 12 WHERE condition = value
L.E: You might need to add apostrophes to strings so I have to change my code to something like this:
$sql = "UPDATE table SET ";
foreach($array as $key=>$value) {
if(is_numeric($value))
$sql .= $key . " = " . $value . ", ";
else
$sql .= $key . " = " . "'" . $value . "'" . ", ";
}
$sql = trim($sql, ' '); // first trim last space
$sql = trim($sql, ','); // then trim trailing and prefixing commas
$sql .= " WHERE condition = value";
which will produce this:
UPDATE table SET id = 3, name = 'NAME', age = 12 WHERE condition = value
L.E 2: If you want the id column in your condition, the code becomes this:
$sql = "UPDATE table SET ";
foreach($array as $key=>$value) {
if($key == 'id'){
$sql_condition = " WHERE " . $key . " = " . $value;
continue;
}
if(is_numeric($value))
$sql .= $key . " = " . $value . ", ";
else
$sql .= $key . " = " . "'" . $value . "'" . ", ";
}
$sql = trim($sql, ' '); // first trim last space
$sql = trim($sql, ','); // then trim trailing and prefixing commas
$sql .= $sql_condition;
which will produce this result:
UPDATE table SET name = 'NAME', age = 12 WHERE id = 3
Hope this helps! :D
foreach ($update_array as $key => $testimonials) {
$name = mysql_real_escape_string($testimonials->name);
$content = mysql_real_escape_string($testimonials->content);
$id = intval($testimonials->id);
$sql = "UPDATE testimonials SET name='$name', content='$content' WHERE id=$id";
$result = mysql_query($sql);
if ($result === FALSE) {
die(mysql_error());
}
}
Source : https://stackoverflow.com/a/7884331/3793639
Other sources to check.
PHP SQL Update array and Simple UPDATE MySQl table from php array
You could use something like this for achieving that:
foreach($values as $value) {
if(!key_exists($value, $item)) {
return false;
}
$table->{$value} = $items[$value];
}
Assuming that the key index is always id and that adodb can use named placeholders you could do this:
$array = Array('id'=>'3', 'name'=>'NAME', 'age'=>'12');
$set = array();
$data = array();
while(list($key,$value)=each($array)) {
$data[':'.$key] = $value;
if($key!='id') {
$set[] = $key . ' = :' . $key;
// if no placeholders use $set[] = $key . " = '" . database_escape_function($value) . "'";
}
}
$sql = "UPDATE table SET ".implode($set, ',')." WHERE id=:id";
//$data is now Array(':id'=>'3', ':name'=>'NAME', ':age'=>'12');
//$sql is now "UPDATE table SET name=:name, age=:age WHERE id=:id";
$stmt = $DB->Prepare($sql);
$stmt = $DB->Execute($stmt, $data);
This is probably the shortest and easiest for you, you can also use something like this to achieve it:
$array = Array('id'=>'3', 'name'=>'NAME', 'age'=>'12');
$sql = "UPDATE table SET ";
$sql .= implode(', ', array_map(function($key, $value){
return is_numeric($value) ? "{$key} = {$value}" : "{$key} = '". mysql_real_escape_string($value). "'";
}, array_keys($array), $array));
$sql .= " WHERE id = 123";
// Result : UPDATE table SET id = 3, name = 'NAME', age = 12 WHERE id = 123