I just started php and sql, so this question is probably very silly. I have a database containing nicknames, ids and scores, and I would like to display with php all the nicknames and their corresponding scores, how can I do it ?
So far, I've got this but it only displays one pseudo and its score.
<?php
require 'actions/database.php';
$getAllInfos = $bdd->query('SELECT pseudo, score FROM users');
$getAllInfos->execute(array());
$AllInfos = $getAllInfos->fetch();
?>
<body>
<br><br>
<div class="container">
<h2> scores : </h2>
<br>
<?php echo $AllInfos['pseudo'] ?> : <?php echo $AllInfos['score'] ?>
</div>
By the way, here is the creation of my database :
<?php
$bdd = new PDO('mysql:host=localhost;dbname=seio;charset=utf8;', 'root', 'root');
?>
Thanks a lot for reading :)
See: https://www.php.net/manual/en/pdostatement.fetchall.php
Which will give you an array you can loop though.
Related
I've got two queries going on, one is working fine... Echos all the right column values. The second one shows all the data var_dump but keeps showing Undefined Index. I don't understand what I've done wrong.
I tried to make an array to define the index via the suggestion of a developer but that gave me zero results
$navpage = array();
$navpage['splash_id']='';
etc but that results in the empty space obviously... I don't know why this was the solution I was led to.
Error code says : Notice: Undefined index: splash_id in...
I know there are so many questions like this and most of them are talking about email forms they are working on, while I am just trying to output data from the database.
Here is my query file arts.php
<?php
require 'scripts/start.php';
$pages = $db->query("SELECT article_id, department, title, article_link, shortdesc, img_meta, live FROM content WHERE department='Arts' AND live='Yes'
")->fetchAll(PDO::FETCH_ASSOC);
$navpage = $db->query("SELECT splash_id, page, live, big_message, img1, text1, link1, expdate FROM splash WHERE page='arts' AND live='Yes'
")->fetchAll(PDO::FETCH_ASSOC);
require VIEW_ROOT . '/artpages.php';
?>
The page where I echo things like column - text1
<?php require VIEW_ROOT . '/department/arts_header.php';
?>
<div id="major">
<div id="so" class="mainimage">
<div class="mainimage"><img src="cms_img/header/<?php echo $navpage['img1']?>" class="splashimage"></div>
</div>
<div id="contentbox">
<div id="middle"><div id="articleheadline" class="titlefont"><?php echo $navpage['text1']?></div>
<?php if (empty($pages)): ?>
<p class="textfont">Sorry, there are no articles on this page.</p>
<?php else: ?>
<?php foreach($pages as $page): ?>
<div class="article_container">
<div class="article_promo"><img src="cms_img/<?php echo escape($page['img_meta']) ?>"class="promofit"></div>
<div class="article_title"><span class="article_title_font"><?php echo $page['title']?></span></div>
<div class="article_desc"><span class="article_desc_font"><?php echo $page['shortdesc']?></span></div>
</div><?php endforeach; ?>
<?php endif; ?>
</div></div></div></div>
<?php
require VIEW_ROOT . '/templates/footer.php';
?>
I expect echos of $navpage to fill in like $page does.
Fetch all get a multiple array result so you need to use foreach loop like you did in $pages or use the following code below to fetch only a single array.
$dbh = new PDO("SELECT article_id, department, title, article_link, shortdesc, img_meta, live FROM content WHERE department='Arts' AND live='Yes'");
$stmt = $dbh->prepare("SELECT name FROM mytable WHERE id=4 LIMIT 1");
$stmt->execute();
$navpage= $stmt->fetch();
Because you use ->fetchAll(PDO::FETCH_ASSOC). Its return array of item navpage
So you must to code $navpage[0]['img1'] and $navpage[0]['text1']
Notice check !empty($navpage) before use $navpage[0]
I want to create a PDF using HTML, PHP, and MySQL and I want a new page every time a new row is fetched and then generate a combined PDF for all the pages created.
How can I achieve this?
<?php
$count=0;
$con = mysqli_connect("localhost","root","");
mysqli_select_db($con, "electricity");
$result = mysqli_query($con, "SELECT acct, name, address, amount FROM newtable");
while($row = mysqli_fetch_array($result))
{
?>
<html>
<body><pre>
श्री: <?php echo $row['name'];?><br>
पता: <?php echo $row['address'];?>
ACCNO :- <b><?php echo $row['acct'];?></b>
Amount : <b><?php $val=$row['amount']+25; echo $val;?></b>
</pre>
</body>
</html>
<?php
}
mysqli_close($con);
?>
I used FPDF many times and it allows you to do whatever you want. Have more info here for doc & download link : http://www.fpdf.org/?lang=en
i don't know a lot of php but, i have the following code, it will load all images from the top of the table to the bottom, can i invert this process? load from de bottom to top? I need the ordest lines to be loaded first...
<?php
mysql_connect("localhost","root","");
mysql_select_db("bravo");
$res=mysql_query("select * from coisas");
?>
<div>
<?php
while ($row=mysql_fetch_array($res)) {
echo "<img src=\"{$row['imagem']}\">";
}
?>
</div>
If your table have one identifier column you can do that (assuming id is the identifier column name):
<?php
mysql_connect("localhost","root","");
mysql_select_db("bravo");
$res=mysql_query("SELECT * FROM coisas ORDER BY id DESC");
?>
<div>
<?php
while ($row=mysql_fetch_array($res)) {
echo "<img src=\"{$row['imagem']}\">";
}
?>
</div>
As Mark Baker correctly say, let SQL do it for you with a ORDER BY.
If you still want to do this in PHP, use this snippet of code:
<?php
$html = '';
while ($row=mysql_fetch_array($res)) {
html = "<img src=\"{$row['imagem']}\">".$html;
}
echo $html;
?>
This will concatenate your current (of the loop) fetched array entry with previous one. So, the first will be concatenated before the last (read it as inversed order).
Moreover, don't use msql_* as those functions are deprecated. Use msqli_* or PDO instead
PS.: This code is your code revisited, if there is any error (in fetching array, connection or so) please correct it your own: I only give you a pointer
Please forgive me if I'm going about this the wrong way I don't have much experience in PHP development.
I need to list some real estate listings on a page, which is easy enough, but where I'm having trouble is trying to match them with the proper image. The images are stored on my server and I have the file path saved in one table and all the property info stored in another table.
This is what I have right now and it kind of works.. except for it is showing each listing twice. Once with pic once with out.. I know there has to be a much better way then this..
<?php
$sql="SELECT * FROM $tbl_name, documents_main WHERE show_listing='1' and user_type='1'";
$result=mysql_query($sql);
// Start looping rows in mysql database.
while($rows=mysql_fetch_array($result)){
$payment = $rows['price'] * .09 / 12;
$path = $rows['path'];
$id = $rows['id'];
$note_id = $rows['note_id'];
?>
<div class="row clearfix">
<div style="width: 120px; float: left;">
<?php
if($note_id == $id){
echo "<img src='$path'>";
} else {
echo "";
}
?>
</div>
<div style="float: left;">
<? echo $rows['prop_city']; ?>, $<? echo $rows['price']; ?>$<? echo round($payment); ?>
</div>
</div>
<?
// close while loop
}
?>
I can post the tables if that is helpful.
If you are using two tables in your query, there should be a column in the second table linking the row to a row in the first column
Once you identified this field, write your query like this :
$sql="SELECT * FROM $tbl_name, documents_main WHERE show_listing='1' and user_type='1' and $tbl_name.FIELD_TO_BE_DEFINED = documents_main.ANOTHER_FIELD_TO_BE_DEFINED";
Or :
$sql="SELECT * FROM $tbl_name inner join documents_main on $tbl_name.FIELD_TO_BE_DEFINED = documents_main.ANOTHER_FIELD_TO_BE_DEFINED WHERE show_listing='1' and user_type='1'";
I'm currently working on a quiz program using PHP/mySQL (my first time ever actually using either).
Up until now I was just working on getting it all functioning correctly with the mySQL tables, and to do so I was putting all questions in a quiz on one page. However, now I want to be able to put just one question per page and then progress by submitting one answer at a time.
The way my questions are chosen to be in the quiz may be a little confusing. They all have a "quiz_id" column that corresponds to the quiz they're in. The quiz has a "length" column that specifies how many questions it will actually have. So there can be more questions with the corresponding "quiz_id" than will actually be in the quiz. The way I randomly select which questions will be included is with "$question = "SELECT * FROM questions WHERE quiz = '$id' ORDER BY rand() LIMIT $length";".
Now I'm having a lot of trouble putting just one question per page. This is because each time you progress, the next random question needs to be chosen, as long as we haven't reached the limit of $length number of questions. A counter also needs to increase that keeps track of what number question you are on, out of how many ($length). I'm not sure if I need to have two separate action scripts.. one to begin the quiz, and then one to progress between questions.
Here's my quiz.php page (start page for any quiz):
<?php
// initialize the mysql data
$connect = mysql_connect('localhost', 'root', '');
$select_db = mysql_select_db('mysql');
// define the id and length from url
$id = mysql_real_escape_string($_GET['id']);
$length = mysql_real_escape_string($_GET['length']);
// query quiz table for all columns
$query_quiz = "SELECT * FROM quizzes WHERE id = '$id' LIMIT 1";
// if quiz query fails
if(!$query_quiz_result = mysql_query($query_quiz))
{
die("Couldn't run quiz query");
}
// fetch whole array of quiz info
$quiz = mysql_fetch_array($query_quiz_result);
//query question table for all columns
$question = "SELECT * FROM questions WHERE quiz = '$id' ORDER BY rand() LIMIT $length";
$q_result = mysql_query($question) or die ("couldn't run questions query");
// store queried questions as an array to pass via session variables
$q_array = array();
while($row = mysql_fetch_assoc($q_result))
{
$q_array[] = $row;
}
session_start();
$_SESSION['quiz'] = $id;
$_SESSION['questions'] = $q_array;
$_SESSION['length'] = $length;
?>
<html>
<head>
<title>Quiz <?php echo mysql_real_escape_string($_GET['id']);?></title>
<link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div id="container" style="margin-left: 30px;">
<!-- create the header using the quiz id and name -->
<h1 style="text-align: center;">Quiz <?php echo $quiz['id'] ?>: <?php echo $quiz['name'] ?></h1>
<hr />
<h4>This quiz will have a total of <?php echo $length?> questions.</h4>
<button onClick="parent.location='start.php'">Begin Quiz</button>
</div>
<script src="js/bootstrap.min.js"></script>
</body>
</html>
And here's my start.php page.. not sure if I can use this one page for all the questions, or do I need a separate action page for once the quiz has begun and you're progressing past #1?
<?php
// continue the session
session_start();
// initialize the mysql data
$connect = mysql_connect('localhost', 'root', '');
$select_db = mysql_select_db('mysql');
$quiz_id = $_SESSION['quiz'];
$length = $_SESSION['length'];
$_SESSION['questions_array'] = $_SESSION['questions'];
$current_question = array_shift($_SESSION['questions_array']);
$_SESSION['counter'] = 1;
$counter = $_SESSION['counter'];
?>
<html>
<head>
<title>Quiz <?php echo mysql_real_escape_string($_GET['id']);?></title>
<link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div id="container" style="margin-left: 30px;">
<h3>Question <?php echo $counter ?> of <?php echo $length ?></h3>
<hr />
<h4><?php echo $current_question['prompt']?></h4>
<?php
// define query for answers for each question
$answers = 'SELECT `prompt` FROM `answers` WHERE `quiz` = '.$quiz_id.' AND `question` = '.$current_question['id'].'';
//if failed
if(!$answers_result = mysql_query($answers)){
die("Couldn't run answers query");
}
?>
<p style="margin-left: 50px;">
<?php
// if question type is "multiple choice", loop through answer choices and print them as options
if ($current_question['if_short_answer'] == 0) {
// loop through rows of answer choices
while($a_row = mysql_fetch_array($answers_result))
{
// print each answer choice
?>
<input type='radio' name='question_<?php echo $current_question['id']; ?>' value='<?php echo $a_row['prompt']?>'><?php echo $a_row['prompt']?>
<br />
<?php
}
echo "</p>";
}
// if question type is "short answer", create text box
elseif ($current_question['if_short_answer'] == 1) {
?>
<input type="text" name="question_<?php echo $current_question['id']; ?>" /><br />
</p>
<?php
} ?>
<?php
if ($counter >= 1) { ?>
<button onClick="parent.location='next.php'">Next Question</button>
<?php
}
else { ?>
<button onClick="parent.location='start.php'">Begin Quiz</button>
<?php
}
?>
</div>
<script src="js/bootstrap.min.js"></script>
</body>
</html>
I apologize if this is a very vague or long question.. I've just gotten myself pretty lost now and not sure how to proceed. Basically I am asking: how can I put just one question per page, progressing through random questions until a limit of $length is reached, and then a "submit quiz" button at the end leads to a score page? All along the way, the "next question" button needs to store the user's input for the current question.
I basically need guidance in writing my script to progress from one question to the next.
Thanks!
All you need to get the all questions from Database, and using jquery show()/hide() method show only one questions at a time.
I had written sample script for your requirement here.
http://www.smarttutorials.net/responsive-quiz-application-using-php-mysql-jquery-ajax-and-twitter-bootstrap/
Firstly you are re creating the $q_array on each page so it will only contain the last displayed question which will not work
try
if(isset($_SESSION['questions']))
{
$_SESSION['questions']+= ", $question_id";
}
In the select query you should omit the questions with the already displayed in the array.