MySQL/Php: nonrepeating random selection with unique ID selectors - php

I'm new to using php and mysqp.
Using the code below, I am calling and echoing four names from a mysql database (in a 'names' column) without repeat.
However, what I'd like to do is assign a unique CSS id selector to each name.
The intent is to have four individually styled boxes around the page, each with a different name chosen randomly upon load.
What would be the best code to do this?
(Fyi I am using an xxamp installation.)
Thanks!
<?php
$sandbox = mysql_connect("localhost", "root", "password")
or die(mysql_error());
mysql_select_db("sandbox", $sandbox);
$sql = "SELECT * FROM names ORDER BY RAND() LIMIT 4";
$result = mysql_query($sql, $sandbox);
while ($row = mysql_fetch_array ($result)) {
$name1 = $row['Name'];
echo $name1 . '<br>' ;
}

Would this work for you:
<?php
$sandbox = mysql_connect("localhost", "root", "password")
or die(mysql_error());
mysql_select_db("sandbox", $sandbox);
$sql = "SELECT * FROM names ORDER BY RAND() GROUP BY Name LIMIT 4";
$result = mysql_query($sql, $sandbox);
$i = 0;
while ($row = mysql_fetch_array ($result)) {
echo '<div id=box"'.$i++.'">'.$row['Name'].'</div>';
}
This gives you an unique CSS selector using the primary key in your table?

This should work.
$sandbox = mysql_connect("localhost", "root", "password")
or die(mysql_error());
mysql_select_db("sandbox", $sandbox);
$sql = "SELECT * FROM names ORDER BY RAND() LIMIT 4";
$result = mysql_query($sql, $sandbox);
$i = 0;
while ($row = mysql_fetch_array ($result)) {
$id = $row['ID'];
echo '<div id=box"'.$i++.'">your content</div>';
}

Related

How to get total number of row by using this function php mysql?

How to get total number of row by using this function php mysql ?
i use this code for display data from mysql. It's work good,
Buy i want to know can i get total number of row by using this code ?
<?PHP
include("connect.php");
$query = "SELECT * FROM table";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$id = $row['id'];
}
?>
Try this mysql_num_rows ($result)
Use this line of code
<?PHP
include("connect.php");
$query = "SELECT * FROM table";
$result = mysql_query($query) or die(mysql_error());
$number_of_rows = mysql_num_rows($result); // this will return the number of rows found by the $result query.
echo $number_of_rows;
while($row = mysql_fetch_array($result))
{
$id = $row['id'];
}
?>

retrieving specific rows from a table and storing each row as an associative array in session

I am creating a PHP/MSQL Application which is basically an online quiz, user will start quiz, internally for an instance randomly 30 questions are retrieved from db-table and stored in session. My database table has qid, question, op1, op2, op3, op4, ans, category as columns (as every question should have 4 options and one answer).
I want to retrieve all(for an instance 30) question stored in the table of an specific category and save them in session variables as 2/3-dimensional associative array using some loop say while()/for() etc.
The script i've written yet is,
session_start();
require 'connection.php';
$sql = "SELECT * FROM questions WHERE category='$category'";
$result = mysql_query($sql) or die(mysql_error());
$found=mysql_num_rows($result) or die(mysql_error());
if ($found!=0) {
$i="1";
$sql= "SELECT * FROM questions WHERE category='$category'";
$result = mysql_query($sql) or die(mysql_error());
while ($que= mysql_fetch_assoc($result) && $i<=$found) {
$_SESSION["$i"]= array(
"question"=>$que['question'],
"op1"=>$que['op1'],
"op2"=>$que['op2'],
"op3"=>$que['op3'],
"op4"=>$que['op4'],
"ans"=>$que['ans']
);
$i++;
}
echo $_SESSION["$i"]; // echo-ing some session variable
}
mysql_close($dbc);
I had also used the script given below for achieving the same thing earlier but there was no success-
session_start();
require 'connection.php';
$sql = "SELECT * FROM questions WHERE category='$category'";
$result = mysql_query($sql) or die(mysql_error());
$found=mysql_num_rows($result) or die(mysql_error());
if ($found!=0) {
$i="1";
$result1 = mysql_query($sql) or die(mysql_error());
$_SESSION['que'][][]=array();
while ($que= mysql_fetch_assoc($result1) && $i<=$found) {
$_SESSION['que'][$i]['question']=$que['question'];
$_SESSION['que'][$i]['op1']=$que['op1'];
$_SESSION['que'][$i]['op2']=$que['op2'];
$_SESSION['que'][$i]['op3']=$que['op3'];
$_SESSION['que'][$i]['op4']=$que['op4'];
$_SESSION['que'][$i]['ans']=$que['ans'];
$i++;
}
}
mysql_close($dbc);
Finally i could do this using below code-
session_start();
require 'connection.php';
$sql = "SELECT * FROM questions WHERE category='$category'";
$result = mysql_query($sql) or die(mysql_error());
$found=mysql_num_rows($result) or die(mysql_error());
if ($found!=0) {
$i="1";
$result1 = mysql_query($sql) or die(mysql_error());
while ($que= mysql_fetch_assoc($result1) && $i<=$found) {
$str="que".$i;
$_SESSION[$str]['qno']=$i;
$_SESSION[$str]['question']=$que['question'];
$_SESSION[$str]['op1']=$que['op1'];
$_SESSION[$str]['op2']=$que['op2'];
$_SESSION[$str]['op3']=$que['op3'];
$_SESSION[$str]['op4']=$que['op4'];
$_SESSION[$str]['ans']=$que['ans'];
$_SESSION[$str]['opt']="0";
$i++;
}
}
mysql_close($dbc);
Give this to try.
require 'connection.php';
session_start();
$sql = "SELECT * FROM questions WHERE category='$category'";
$result = mysql_query($sql) or die(mysql_error());
$found=mysql_num_rows($result) or die(mysql_error());
if ($found!=0) {
$i=1;
$sql= "SELECT * FROM questions WHERE category='$category'";
$result = mysql_query($sql) or die(mysql_error());
while ($que= mysql_fetch_assoc($result) && $i<=$found) {
$_SESSION[$i]= array(
"question"=>$que['question'],
"op1"=>$que['op1'],
"op2"=>$que['op2'],
"op3"=>$que['op3'],
"op4"=>$que['op4'],
"ans"=>$que['ans']
);
}
print_r($_SESSION[$i]);
$i++;
}
mysql_close($dbc);

How to view last inserted value of auto increment field

In my database I have a field called spaj_per as an auto increment primary key.
How can I display the lastest inserted value in the field spaj_per. I tried this.
<?php
$con = mysql_connect("localhost", "SuperAdmin", "***");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db("sistem_pengurusan_fail",$con);
$q = "SELECT MAX(id) AS spaj_per FROM unit_pengambilan";
$result = mysql_query($q);
$row = mysql_fetch_array($result);
?>
<?php echo $row['spaj_per']; ?>
But it won't work.
You may use
SELECT id FROM mytable ORDER BY id DESC LIMIT 1;
or like
$last_id = mysql_insert_id();
Try this,
$q = "SELECT MAX(spaj_per) AS spaj_per FROM unit_pengambilan";
$result =mysql_query($q);
$row = mysql_fetch_row($result);
echo $row[0];
Use PHP's mysql_insert_id() function
Try the following
<?
$q = "SELECT MAX(spaj_per) AS last_spaj_per FROM unit_pengambilan";
$result =mysql_query($q);
$row = mysql_fetch_array($result);
echo $row['last_spaj_per'];
?>
$row = mysql_fetch_array($result); Change to $row = mysql_fetch_assoc($result); and try
Try with mysql_insert_id
For more reference use following link
http://php.net/manual/en/function.mysql-insert-id.php

php mysql is this correct?

Is this Query and display info all correct? Syntax-wise.
<?php
mysql_connect("HOST", "USERNAME", "PASSWORD") or die (mysql_error ());
mysql_select_db("DATABASENAME?!?!") or die(mysql_error());
$strSQL = "SELECT * FROM TABLENAME";
$result = mysql_query($strSQL) or die(mysql_error());
while($row = mysql_fetch_array($result)) {
echo $row['COLUMNNAME'] . "<br />";
}
mysql_close()
?>
Use statement as
<?php
$conn=mysqli_connect("HOST", "USERNAME", "PASSWORD") or die (mysqli_error ());
mysqli_select_db("DATABASENAME",$conn) or die(mysqli_error());
$strSQL = "SELECT * FROM TABLENAME";
$result = mysqli_query($strSQL) or die(mysqli_error());
while($row = mysqli_fetch_array($result)) {
echo $row['COLUMNNAME'] . "<br />";
}
mysqli_close()
?>
Also I advice you to use Mysqli or Pdo instead of Mysql driver as it is deprecated.
There is no issue in your question or code. Syntax wise it is fine. But it is advised not to use mysql_* functions because it is deprecated.
The general way of using the code for your condition would be:
<?php
mysqli_connect("HOST", "USERNAME", "PASSWORD") or die (mysqli_error());
mysqli_select_db("DATABASENAME") or die(mysqli_error());
$strSQL = "SELECT * FROM TABLENAME";
$result = mysqli_query($strSQL) or die(mysqli_error());
while($row = mysqli_fetch_array($result)) {
foreach ($row as $column => $value)
echo $column . " = " . $value . "<br />";
echo "<br/>";
}
mysqli_close();
?>
So, this iterates and suppose say you have four columns, and two rows, it gives an output like:
Column 1 Name = Value
Column 2 Name = Value
Column 3 Name = Value
Column 4 Name = Value
Column 1 Name = Value
Column 2 Name = Value
Column 3 Name = Value
Column 4 Name = Value

How to add all the rows of a column into a variable?

Imagine I had an "id" column and each of its rows contained a number. Lets say I have 3 rows at the moment. row 1 contains 1111, row 2 contains 2222, row 3 contains 3333.
I want to get the row values into a variable, and separate each row's data by a comma. The final result I expect is $variable = 1111,2222,3333.
I got this far code-wise:
<?php
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("streamlist") or die(mysql_error());
$sql = mysql_query("SELECT web_id FROM streams") or die(mysql_error());
while($row = mysql_fetch_array($sql)) {
$streamlist = $row['web_id'].",";
echo $streamlist;
}
?>
The problem is that I then need each row's information singularly:
<?php
$numbers = explode(',', $streamlist);
$firstpart = $numbers[0];
echo $firstpart;
?>
And the above code doesn't work inside the while() statement, nor does this:
<?php
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("streamlist") or die(mysql_error());
$sql = mysql_query("SELECT web_id FROM streams") or die(mysql_error());
while($row = mysql_fetch_array($sql)) {
$streamlist = $row['web_id'].",";
}
$numbers = explode(',', $streamlist);
$firstpart = $numbers[0];
echo $firstpart;
?>
So basically, how can I get all of the information of the rows into a variable, and make them seperated by commas, in order to then get each number singularly?
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("streamlist") or die(mysql_error());
$sql = mysql_query("SELECT web_id FROM streams") or die(mysql_error());
while($row = mysql_fetch_assoc($sql)) {
$streamlist[] = $row['web_id'];
}
foreach ($streamlist as $row) {
// Do whatever you want with the data
echo $row.',';
}
$comma_separated = implode(",", $streamlist);
You're on the right track, try this on for size:
<?php
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("streamlist") or die(mysql_error());
$sql = mysql_query("SELECT web_id, nextrow, nextrow2 FROM streams") or die(mysql_error());
while($row = mysql_fetch_array($sql, MYSQL_NUM)){
// $array_data will contain the array with all columns from the query (usable for your individual data needs as well)
$array_data[] = $row;
$var_string .= implode(",",$row);
// $var_string will contain your giant blob comma separated string
}
echo "<pre>"; print_r($array_data);echo "</pre>";
echo $var_string;
// These are for outputting the results
?>
The $streamlist scope doesn't seem right. Try:
$streamlist = '';
while($row = mysql_fetch_array($sql)) {
$streamlist .= $row['web_id'].",";
}

Categories