Reputation: 341
I am new to PHP and I am trying to print out 5 pictures to which the references are stored inside a string, separated by new line.
Here's what I have so far :
function displayTeam($heroes){
$herolist = array();
$conn = odbc_connect('Dotalyzer', '', '');
if (!$conn) {
exit("Connection Failed: " . $conn);
}
$sql = "SELECT * FROM HeroStats ORDER BY Heroname";
$rs = odbc_exec($conn, $sql);
if (!$rs) {
exit("Error in SQL");
}
foreach(preg_split("/((\r?\n)|(\r\n?))/", $heroes) as $line){
while (odbc_fetch_row($rs)) {
$heroname = odbc_result($rs, "HeroName");
if ($line == $heroname) {
$heroimage = odbc_result($rs, "Portrait");
$herolist[] = $heroimage . ".png";
}
}
}
odbc_close($conn);
echo " <div class='heroimage_wrapper'>";
for ($i = 0; $i < 5; $i++) {
echo " <img src='Hero icons/$herolist[$i]' class='heroimage'>";
}
echo " </div>";
}
I want to print each picture from the array, the references are stored in an Access database.
I am calling the function which generates my $heroes
string using:
$(document).ready(function(){
$('.button').click(function(){
var clickBtnValue = $(this).val();
var id = $(this).attr('data-unique-id');
var ajaxurl = 'ajax/ajax',
data = {
'action': clickBtnValue,
'id': id
};
console.log(clickBtnValue);
$.post(ajaxurl, data, function (response) {
// Response div goes here.
alert(response.replace('\\n', '\n'));
});
});
});
Upvotes: 0
Views: 90
Reputation:
I can see two errors in your code.
First:
Change this
$herolist[] .= $heroimage . ".png";
to
$herolist[] = $heroimage . ".png";
Second:
Remove .png from img src attribute and update for loop to use array length
for ($i = 0; $i < 5; $i++) {
echo " <img src='Hero icons/$herolist[$i].png' class='heroimage'>";
}
to
for ($i = 0; $i < count($herolist); $i++) {
echo " <img src='Hero icons/$herolist[$i]' class='heroimage'>";
}
Also, you should not use spaces for folder names. Change your folder name from Hero icons to Hero_icons and update the img tag.
Upvotes: 0
Reputation: 1175
You can get 5 DB entities with LIMIT
operation. Such as
$query = 'SELECT * FROM HeroStats ORDER BY Heroname LIMIT 5'
You can use mysqli
to connect Database
$db_connection = new mysqli([HOST], [USERNAME], [PASSWORD], [DATABASE_NAME]);
Use mysqli::fetch_array
to fetch images to an array. This function will help you
function fetch($query)
{
$res = $db_connection->query($query);
$array = [];
while( $r = $res->fetch_array(MYSQLI_ASSOC) )
{
array_push($array, $r);
}
return $array;
}
To pass array into Javascript, encode array to JSON or xml
$array = fetch($query);
$json = json_encode($array);
So, you can receive this response in Javascript, just convert JSON to array
var images = JSON.parse(response);
Upvotes: 1