Trying to do a translation of my MySQL DB to PHP.
Here's the code:
$sql = "SELECT Name, Price FROM utf WHERE Name LIKE 'K%'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<div class=\"CSSTableGenerator style=\"width:600px;height:150px;\"><table><tr><th>Name</th><th>Price</th></tr></div>";
// output data of each row
while($row = $result->fetch_assoc()) {
$name = str_replace('K', 'Karambit', $row['Name']);
echo "<tr><td>".$name."</td><td>".$row["Price"]." ".$row["Trend"]."</td></tr>";
}
echo "</table>";
So Select, Filter by signature character, and then translate.
Now, I have a lang.php file which has the translations.
Here it is:
<?php
function lang($phrase){
static $lang = array(
'ba' => 'Bayonet',
'ka' => 'Karambit'
);
return $lang[$phrase];
}
?>
How do I put it in this line:
$name = str_replace('K', 'Karambit', $row['Name']);
and replace 'ka' => 'Karambit' with 'Karambit'?
Non of these have worked:
//attempt 1
$name = str_replace('K', 'lang('ka');', $row['Name']);
//attempt 2
$name = str_replace('K', '$lang('ka');', $row['Name']);
//attempt 3
$word = echo lang('ka');
$name = str_replace('K', '$word', $row['Name']);
Don't put function calls in quotes, just use:
$name = str_replace('K', lang('ka'), $row['Name']);
//^^^^^^^^^^ See here
Also to give you another option:
You can store your search => replace values into an array like this:
$searchReplace = [
"ba" => "Bayonet",
"ka" => "Karambit",
];
And then you can simply use strtr() to replace it, e.g.
$name = strtr($row['Name'], $searchReplace);
Related
I want to select the database more values (I already did) and be converted to JSON
I tried all
php
$a = $_GET['name'];
header('Content-Type: application/json');
echo '{"results":[';
$selectSearch = "SELECT * from `users` WHERE `name` LIKE '".$a["term"]."%'";
$rezultatul = $db->query($selectSearch);
if ($rezultatul->num_rows > 0) {
while($row = $rezultatul->fetch_assoc()) {
$name = $row["name"];
$arr = array('id' => $row["id"], 'text' => $row["name"], 'level' => $row["Level"]);
echo json_encode($arr);
}
}
echo ']}';
And he looks like this:
{"results":[{"id":"1","text":"Pompiliu","level":"7"}
{"id":"11","text":"Pompiliu1","level":"100"}]}
But between the two must be like that
{"id":"1","text":"Pompiliu","level":"7"},
{"id":"11","text":"Pompiliu1","level":"100"}
And when there will be 3 results
{"id":"1","text":"Pompiliu","level":"7"},
{"id":"11","text":"Pompiliu1","level":"100"},
{"id":"12","text":"Pompiliu2","level":"100"}
Add to the array with [] and then json_encode.
Don't try and build json strings on your own.
if ($rezultatul->num_rows > 0) {
while($row = $rezultatul->fetch_assoc()) {
$name = $row["name"];
$arr[] = array('id' => $row["id"], 'text' => $row["name"], 'level' => $row["Level"]);
}
}
echo json_encode(["results" => $arr]);
I'm trying to make a json output from my db in php with all of users from sql table but i don't know how to do that..i'm new with this.
I want the code to output like this.
[
{
"name": "Maybell",
"avatar": "zeldman/128.jpg",
"data": {
"company": "Alibaba",
"title": "Engineer"
}
}
]
but the my code does the following output and is not ok.
{
"name": "Maybell",
"avatar": "zeldman\/128.jpg",
"company": "alibaba"
"title": "Engineer"
}
Here is the Php code:
<?php
header("Content-type: text/json");
$db = mysqli_connect("localhost","root","","testest");
//MSG
$query = "SELECT * FROM mls_users LIMIT 20";
$result = mysqli_query($db, $query);
//Add all records to an array
$rows = array();
while($row = $result->fetch_array()){
$name = $row['name'];
$avatar = $row['avatar'];
$company= $row['company'];
$title= $row['title'];
}
//Return result to jTable
$qryResult = array();
$qryResult['name'] = $name;
$qryResult['avatar'] = $avatar;
$qryResult['company'] = $company;
$qryResult['title'] = $title;
echo json_encode($qryResult,JSON_PRETTY_PRINT);
mysqli_close($db);
?>
Just change:
//Add all records to an array
$rows = array();
while($row = $result->fetch_array()){
$name = $row['name'];
$avatar = $row['avatar'];
$company= $row['company'];
$title= $row['title'];
}
//Return result to jTable
$qryResult = array();
$qryResult['name'] = $name;
$qryResult['avatar'] = $avatar;
$qryResult['company'] = $company;
$qryResult['title'] = $title;
To:
//Add all records to an array
$qryResult = [];
while ($row = $result->fetch_array()) {
$qryResult[] = [
'name' => $row['name'],
'avatar' => $row['avatar'],
'data' => [
'company' => $row['company'],
'title' => $row['title'],
],
];
}
You can skip setting the intermediate variables and just add onto the $qryResult array directly.
try this:
<?php
header("Content-type: text/json");
$db = mysqli_connect("localhost","root","","testest");
//MSG
$query = "SELECT * FROM mls_users LIMIT 20";
$result = mysqli_query($db, $query);
//Add all records to an array
$users = array();
while($row = $result->mysqli_fetch_assoc()){
$users[] = [
'name' => $row['name'],
'avatar' => $row['avatar'],
'data' => [
'company' => $row['company'],
'title' => $row['title']
]
]
}
echo json_encode($users,JSON_PRETTY_PRINT);
mysqli_close($db);
?>
I changed fetch_row() to mysqli_fetch_assoc() and then actually made an array with all fetched rows. You kind of wanted to do that i can see that in comments but you didnt. Then just json encode it.
The outlining brackets [ and ] should come automatically when the array has multiple elements in it.
You are almost there, you just need to wrap it in an array and make data an array.
$qryResult = array();
$qryResult['name'] = $name;
$qryResult['avatar'] = $avatar;
// Now make an array to hold data
$data = array();
$data['company'] = $company;
$data['title'] = $title;
// Add data to qryResult
$qryResult['data'] = $data
// Wrap qryResult in array so output will be wrapped in array
$outPutResults = array($qryResult);
echo json_encode($outPutResults,JSON_PRETTY_PRINT);
$qryResult = array();
$qryResult['name'] = $name;
$qryResult['avatar'] = $avatar;
$qryResult['data']['company'] = $company;
$qryResult['data']['title'] = $title;
Try that way. You are asking for a multidimensional-array so you need to set it up as one.
Succesfully solved: Working code is noted at the bottom of this Post.
I'm currently trying to run a SQL command to grab all the data out of a database table and send it over a API call using the variable names.
The problem I'm having is assigning the values of the fields under "$row" to separate variables so I can then place them in my foreach loop and send them all over to the API call. Can anyone enlighten me to what I'm doing wrong
I'm sure the line that I'm going wrong is my commandbuilder and then assigning the variables to the data inside row.
I feel like the problem line could be
while ($row = mysql_fetch_assoc()) {
$emails = $row['email_address'];
$names = $row['forename'];
}
the full code is below.
public function actionImportSubscribers($cm_list_id){
//need to pass through cm_list_id instead
$cm_list_id = Yii::app()->getRequest()->getQuery('cm_list_id');
$model =$this->loadModelList($cm_list_id);
$listID = $model->cm_list->cm_list_id;
$row = Yii::app()->db->createCommand()
->select('email_address, forename')
->from('tbl_cm_subscribers')
->where('cm_list_id=:id', array(':id' => $cm_list_id))
->queryAll();
while ($row = mysql_fetch_assoc()) {
$emails = $row['email_address'];
$names = $row['forename'];
}
$customFieldArray = array();
$addFieldsToList = array();
foreach (array_combine($emails, $names) as $name => $email) {
$addFieldsToList[] = array('EmailAddress' => $email,'Name' => $name,'CustomFields' => $customFieldArray);
}
$auth = array('api_key' => '');
$wrap = new CS_REST_Subscribers($listID, $auth);
$result = $wrap->import(array($addFieldsToList), false);
Working code is below
public function actionImportSubscribers($cm_list_id){
//need to pass through cm_list_id instead
$cm_list_id = Yii::app()->getRequest()->getQuery('cm_list_id');
$model =$this->loadModelList($cm_list_id);
$listID = $model->cm_list->cm_list_id;
$result = Yii::app()->db->createCommand()
->select('email_address, forename')
->from('tbl_cm_subscribers')
->where('cm_list_id=:id', array(':id' => $cm_list_id))
->queryAll();
$emails=array();
$names=array();
foreach ($result as $row) {
$emails[] = $row['email_address'];
$names[] = $row['forename'];
}
require_once 'protected/extensions/createsend-php-5.0.1/csrest_subscribers.php';
$auth = array('api_key' => '');
foreach (array_combine($emails, $names) as $email => $name) {
$wrap = new CS_REST_Subscribers($listID, $auth);
$result = $wrap->import(array(
array(
'EmailAddress' => $email,
'Name' => $name,
),
), false);
}
echo "Result of POST /api/v3.1/subscribers/{list id}/import.{format}\n<br />";
if($result->was_successful()) {
echo "Subscribed with results <pre>";
var_dump($result->response);
} else {
echo 'Failed with code '.$result->http_status_code."\n<br /><pre>";
var_dump($result->response);
echo '</pre>';
if($result->response->ResultData->TotalExistingSubscribers > 0) {
echo 'Updated '.$result->response->ResultData->TotalExistingSubscribers.' existing subscribers in the list';
} else if($result->response->ResultData->TotalNewSubscribers > 0) {
echo 'Added '.$result->response->ResultData->TotalNewSubscribers.' to the list';
} else if(count($result->response->ResultData->DuplicateEmailsInSubmission) > 0) {
echo $result->response->ResultData->DuplicateEmailsInSubmission.' were duplicated in the provided array.';
}
echo 'The following emails failed to import correctly.<pre>';
var_dump($result->response->ResultData->FailureDetails);
}
echo '</pre>';
// }
}
I don't know if this solving your problem but you have few errors there.
mysql_fetch_assoc() requires param , resource returned from mysql_query function.
In part where you creating $emails and $names variables you doing that like if you trying to create array but you will get always single value in that way how you have done it. This is example if you will use mysql_fetch_assoc, you can't combine queryAll() with mysql_fetch_assoc
$emails=array();
$names=array();
$result=mysql_query("SELECT email_address, forename FROM tbl_cm_subscribers where cm_list_id='$cm_list_id'");
while ($row = mysql_fetch_assoc($result)) {
$emails[] = $row['email_address'];
$names[] = $row['forename'];
}
queryAll() method returns array, I don't know Yii but I suppose this is what you need to do
$result = Yii::app()->db->createCommand()
->select('email_address, forename')
->from('tbl_cm_subscribers')
->where('cm_list_id=:id', array(':id' => $cm_list_id))
->queryAll();
$emails=array();
$names=array();
foreach ($result as $row) {
$emails[] = $row['email_address'];
$names[] = $row['forename'];
}
Or if you don't need array of results then use $emails and $names without []
How can I echo out value after the while loop. If I do the echo in below code its says Undefined index.
$sql_cast = "SELECT *
FROM
title_cast
INNER JOIN title ON (title_cast.id_title = title.id)
INNER JOIN `cast` ON (title_cast.id_cast = `cast`.id)
WHERE
title_cast.id_title = '1'";
$result_cast = mysql_query($sql_cast) or die('log error with' .mysql_error());
$cast = array();
while ($row = mysql_fetch_assoc($result_cast)) {
$id = $row['id'];
$name = $row['name'];
$img = $row['photo_localurl'];
$poster = str_replace("./", "lib/", $img);
$cast[] = array('id' => $id, 'name' => $name, 'img' => $poster);
//$cast[] = $row;
}
//var_dump($cast);
echo $cast['id'] . " " . $cast['name'] . " " . $cast['poster']."<br />";
Within the while loop, you set the cast array content using $cast[] syntax. This will create a numerical index, starting at 0, then 1 and so on, so you're creating an array that looks like this:
$cast = array(
0 => array('id' => $id, 'name' => $name, 'img' => $poster),
1 => array('id' => $id, 'name' => $name, 'img' => $poster)
);
You need to include the numerical key of the array that you want to echo. For example, if you want to echo the first row:
echo $cast[0]['id']; // Echo the id of the first result
If you want to echo ALL of the rows, use foreach:
foreach($cast as $row) {
echo $row['id'];
}
Maybe you should do:
$cast = array('id' => $id, 'name' => $name, 'img' => $poster);
//$cast[] = $row;
}
//var_dump($cast);
echo $cast['id'] . " " . $cast['name'] . " " . $cast['poster']."<br />";
because if you use $cast[], it will append the new array to your array..
That's because you are pushing a new array in $cast at each index..
So you should echo like this..
$i = 0;
while ($row = mysql_fetch_assoc($result_cast)) {
$id = $row['id'];
$name = $row['name'];
$img = $row['photo_localurl'];
$poster = str_replace("./", "lib/", $img);
$cast[] = array('id' => $id, 'name' => $name, 'img' => $poster);
//$cast[] = $row;
//var_dump($cast);
echo $cast[$i]['id'] . " " . $cast[$i]['name'] . " " . $cast[$i]['poster']."<br />";
$i++;
}
Try this:
<?php
while ($row = mysql_fetch_assoc($result_cast)) {
$id = $row['id'];
$name = $row['name'];
$img = $row['photo_localurl'];
$poster = str_replace("./", "lib/", $img);
$cast[] = array('id' => $id, 'name' => $name, 'img' => $poster);
}
foreach($cast as $rows) {
echo $rows['id']." ".$rows['name']." ".$rows['img']."<br />";
}
?>
print_r($cast[0]); or you can use $cast[0]['id'] ;
There are two problems with your code, First is that $cast[] is a two-dimensional array so it contains arrays at each of its index, so you must use
$cast[$i]['id']
Where i will be the counter variable that will iterate through all the indexes. Secondly change
$cast['poster']
to
$cast['img']
Hope this helps.
I have the following code
while($row = $usafisRSP->fetch_assoc()) {
$id = $row['id'];
$Applicantid = $row['Applicantid'];
$unique_num = $row['unique_num'];
// .................
$hidden_fields = array($Applicantid, $unique_num, $regs_t ....);
$hidden_values = array();
foreach ($hidden_fields as $key => $value) {
$hidden_values[$value] = "$key = ".base64_decode($value)."<br>";
echo $hidden_values[$value];
}
}
and the result is something like this
0 = 116153840
1 = 136676636
2 = 2010-12-17T04:12:37.077
3 = XQ376
4 = MUKANTABANA
I would like to replace 0, 1, 2, 3 etc with some custom values like "Id", "application name" to make the result like
id = 116153840
application name = 136676636
etc ..
how can I do that ?
Replace the $hidden_fields = array(... line with the following:
$hidden_keys = array('id', 'Applicantid', 'unique_num');
$hidden_fields = array_intersect_key($row, array_fill_keys($hidden_keys, NULL));
If you want to suppress all fields with value 0, either use
$hidden_fields = array_filter($hidden_fields, function($v) {return $v != 0;});
(this will completely omit the 0-entries) or
$hidden_fields = array_map($hidden_fields, function($v) {return ($v==0?'':$v);});
(this will leave them blank). If you're using an older version than 5.3, you'll have to replace the anonymous functions with calls to create_function.
I assume not every field in your row should be a hidden field. Otherwise you could just do $hidden_fields = $row.
I would create an array that specifies the hidden fields:
$HIDDEN = array(
'id' => 'Id',
'Applicantid' => 'application name',
'unique_num' => 'whatever'
);
And then in your while loop:
while(($row = $usafisRSP->fetch_assoc())){
$hidden_fields = array();
foreach$($HIDDEN as $field=>$name) {
$hidden_fields[$name] = $row[$field];
}
//...
foreach($hidden_fields as $name => $value) {
$hidden_fields[$name] = $name . ' = ' . base64_decode($value);
echo $hidden_values[$name];
// or just echo $name, ' = ',$hidden_fields[$value];
}
}
foreach ($row as $key => $value) {
$hidden_values[$value] = "$key = ".base64_decode($value)."<br>";
echo $hidden_values[$value];
}
This could give you something relevant. Through accessing the string keys from the row array which contains the string keys