Drag and Drop array NOT EXIST then Insert into MySQL - php

I have two tables one for user and one for search. When I drag a search over to user it adds entire search list. How do I only insert the item dragged and not the entire search array?
THE PROBLEM IS recordsArray.
<?php
require("db.php");
$action = mysql_real_escape_string($_POST['action']);
$updateRecordsArray = $_POST['recordsArray'];
if ($action == "updateRecordsListings"){
$listingCounter = 1;
foreach ($updateRecordsArray as $recordIDValue) {
$query = "UPDATE records1 SET recordListingID = " . $listingCounter . " WHERE recordID = " . $recordIDValue;
mysql_query($query) or die('Error, update query failed');
//INSERTS array item that does NOT EXIT in userTable
if (mysql_affected_rows()==0) {
$query = mysql_query("INSERT INTO records1 SELECT * FROM records WHERE recordID = " . $recordIDValue);
$query = "UPDATE records1 SET recordListingID = " . $listingCounter . " WHERE recordID = " . $recordIDValue;
mysql_query($query) or die('Error, insert/update query failed');
}
$listingCounter = $listingCounter + 1;
}
echo '<pre>';
print_r($updateRecordsArray);
echo '</pre>';
echo 'If you refresh the page, you will see that records will stay just as you modified.';
}
?>
Both list arrays id must maintain the same id names in order for the above item to acknowledge and process the list items. Keeping things simple I just used the same code for the Search, User format:
<li id="recordsArray_<?php echo $result['recordID']; ?>"><?php echo $result['recordID'] . ". " . $result['recordText']; ?></li>
Javascript:
$(function() {
$("#contentLeft ul, #main ul").sortable({ accept: '.draggable', connectWith: "#contentLeft ul", opacity: 0.6, cursor: 'move', update: function() {
var order = $(this).sortable("serialize") + '&action=updateRecordsListings';
$.post("updateDB.php", order, function(theResponse){
$("#contentRight").html(theResponse);
});
}
});
}).disableSelection();
});
How can I call only the recordsArray items from #content ul?

I can only get one insert per refresh with this but it does drag and drop insert...
Still need an if statement for possible errors because +/-1 if
<?php
require("db.php");
$action = mysql_real_escape_string($_POST['action']);
$updateRecordsArray = $_POST['recordsArray'];
$uRA = $updateRecordsArray;
// Get total number of elements in $updateRecordsArray
$ifArray = $updateRecordsArray;
$resultCount = count($ifArray);
//echo '<br />';
//print_r($resultCount);
// Get total number of rows in $records1
$recordTable = array();
$result = mysql_query("SELECT recordListingID FROM records1");
$numRows = mysql_num_rows($result);
while ($row = mysql_fetch_assoc($result)) {
$recordTable = array_merge($recordTable, array_map('trim', explode(",", $row['recordListingID'])));
}
//Gets $id/$val of elements not in both arrays
$results = array_diff($uRA, $recordTable);
//echo '<br />';
//print_r($numRows);
//Give variables for +/- 1 $numRows
$plusNumRows = $numRows + 1;
$minusNumRows = $numRows - 1;
//echo '<br />';
//print_r($minusNumRows);
// Normal jQuery drag and drop ranking found online
if ($action == "updateRecordsListings"){
$listingCounter = 1;
foreach ($updateRecordsArray as $recordIDValue) {
//If statement for for +/- 1 $numRows
If ($resultCount == $numRows -1 || $resultCount == $numRows || $resultCount == $numRows + 1){
$sql = mysql_query("INSERT INTO records1 SELECT * FROM records WHERE recordID = $recordIDValue");
}
$query = "UPDATE records1 SET recordListingID = " . $listingCounter . " WHERE recordID = " . $recordIDValue;
mysql_query($query) or die('Error, update query failed');
$listingCounter = $listingCounter + 1;
}
echo '<pre>';
print_r($updateRecordsArray);
echo '</pre>';
echo 'If you refresh the page, you will see that records will stay just as you modified.';
}
?>

Related

Repeating SQL insert statement in loop till id has certain value?

<?php
include ("db.php");
$id2 = "SELECT MAX(id) FROM osalejad;";
$id = $conn->query($id2);
if (id<= 8){
while($id<= 7) {
$min = 1;
$max = 20;
$suvanumber = rand($min, $max);
$bar = (string) $suvanumber;
$prii= "vaba2" . $bar;
$sql="INSERT INTO osalejad (name) VALUES ('$prii')";
$result = $conn->query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
}
}
else {
echo '8 osalejat on juba kirjas';
}
?>
I have a question, i want to insert data into MYSQl table, word with a random number, but problem is, it never work as it should - if i have 3 records in name column, then till, it adds 8 more records, instead of 5 records. Is something outside of scope atm?
I will use the DB in this code.
<?php
include("db.php");
$sql = "SELECT * FROM `osalejad`;";
$result = $conn->query($sql);
$var = array();
if ($result->num_rows > 0) {
// output data of each row
while ($row = mysqli_fetch_array($result)) {
$var[] = $row["name"];
}
} else {
/// echo "0 results";
}
//shuffle the array, and encode into json.
shuffle($var);
$brack=json_encode($var);
$testbrack= json_encode(array_chunk($var,2));
$final = '{';
$final .= '"teams":';
$final .= $testbrack;
$final .= ',"results":[[[[0,0],[null,null]],[[null,null],[null,null]]]]}';
//updating last tournament bracket.
$sql1 = "UPDATE lan_brackets SET json='$final' ORDER BY tid DESC LIMIT 1;";
$roundOne=$conn->query($sql1);
?>

using only one query to update columns in the database - inplace edit

id car make sales
1 panamera porsche 100
2 italia ferrari 200
3 volante astonmartin 300
4 avantador lamborghini 400
5 slk mercedes 500
So guys, i have this simple table in my database. And i'm gonna echo this table in a while loop.
<ul>
<?php
$query = "SELECT * FROM inplace LIMIT 0, 6";
$result = mysql_query($query) or die ('Query couldn\'t be executed');
while ($row = mysql_fetch_assoc($result)) {
echo '<li class="editable" data-id="'.$row['id'].'" data-col="car">'.$row['car'].'</li>';
echo '<li class="editable" data-id="'.$row['id'].'" data-col="make">'.$row['make'].'</li>';
echo '<li class="editable" data-id="'.$row['id'].'" data-col="sales">'.$row['sales'].'</li>';
}
?>
</ul>
The idea is to update this table using jQuery in-place editor. So here is the code-
$(document).ready(function()
{
$(".editable").bind("dblclick", replaceHTML);
$(".editable2").bind("dblclick", replaceHTML2);
$(".btnSave, .btnDiscard").live("click", handler);
function handler()
{
if ($(this).hasClass("btnSave"))
{
var str = $(this).siblings("form").serialize();
$.ajax({
type: "POST",
async: false,
url: "handler.php",
data: str,
});
}
}
function replaceHTML()
{
var rowId = $(this).parent('li').data('id');
var colName = $(this).parent('li').data('col');
var buff = $(this).html()
.replace(/"/g, """);
$(this).addClass("noPad")
.html("<form><input type=\"text\" name=\"" + colName + "\" value=\"" + buff + "\" /> <input type=\"text\" name=\"buffer\" value=\"" + buff + "\" /><input type=\"text\" name=\"id\" value=\"" + rowId + "\" /></form>Save changes Discard changes")
.unbind('dblclick', replaceHTML);
}
}
);
This is an in-place edit code i got it from the internet and i just tore it down to basic level just to understand the codes. Behrang Saeedzadeh helped me improvise "replace HTML" function.
And here is the update query in handler.php file -
<?php
require("db.php");
if (isset($_POST['id']) && isset($_POST['car'])) {
$id = mysql_real_escape_string($_POST['id']);
$car = mysql_real_escape_string($_POST['car']);
$query = "UPDATE inplace SET car ='$car' WHERE id='$id'";
$result = mysql_query($query) or die ('Query couldn\'t be executed');
if ($result) {echo 1;}
}
else if (isset($_POST['id']) && isset($_POST['make'])) {
$id = mysql_real_escape_string($_POST['id']);
$make = mysql_real_escape_string($_POST['make']);
$query = "UPDATE inplace SET make ='$make' WHERE id='$id'";
$result = mysql_query($query) or die ('Query couldn\'t be executed');
if ($result) {echo 1;}
}
else if (isset($_POST['id']) && isset($_POST['sales'])) {
$id = mysql_real_escape_string($_POST['id']);
$sales = mysql_real_escape_string($_POST['sales']);
$query = "UPDATE inplace SET sales ='$sales' WHERE id='$id'";
$result = mysql_query($query) or die ('Query couldn\'t be executed');
if ($result) {echo 1;}
}
?>
Here in the update query, i have to write a different query for each column. The question is how do i update using only one query for all the columns?
if(isset($_POST['id']) {
$id = mysql_real_escape_string($_POST['id']);
$arr_check = array("car", "make", "sales");
$result = array();
foreach($arr_check as $check) {
if(isset($_POST[$check]))
$result[] = $check . '="' . mysql_real_escape_string($_POST[$check]) . '"';
}
$result = implode(", ", result);
if($result != '') {
$query = "UPDATE inplace SET {$result} WHERE id='{$id}'";
$result = mysql_query($query) or die ('Query couldn\'t be executed');
if ($result) echo 1;
}
}
that should more or less do it
First of all, you might be better off making the entire list a form to begin with, and storing the existing records in hidden form fields. Then, you should have the handler.php script check if any new form entries were submitted, and store them into variables. If no new entry was made, the variables will contain the default value.
Then, you can submit the whole update query in one shot:
$query = "UPDATE inplace SET car ='$car', make='$make', sales='$sales' WHERE id='$id'";
$result = mysql_query($query) or die ('Query couldn\'t be executed');
if ($result) echo 1;

Can't figure out duplicate entries for data in SQL field, and random cell deletion (PHP/MYSQL)

I have an attendance page which outputs a list of students in a class through the following loop:
$sql10 = "SELECT class.name, student_to_class.class_id, student_to_class.student_id
FROM
student_to_class
INNER JOIN
class
ON class.id=student_to_class.class_id
WHERE
class.name = '$classid'";
$result10 = mysql_query($sql10) or die(mysql_error());
while ($row = mysql_fetch_array($result10)) {
$student = $row['student_id'];
$classid = $row['class_id'];
$sql3 = "select * from student where id = '$student'";
$result3 = mysql_query($sql3) or die(mysql_error());
$row3 = mysql_fetch_assoc($result3);
$studentfname = $row3['first_name'];
$studentlname = $row3['last_name'];
$sql4 = "select * from student where first_name = '$studentfname' AND last_name = '$studentlname'";
$result4 = mysql_query($sql4) or die(mysql_error());
$row4 = mysql_fetch_assoc($result4);
$studentrfid = $row4['rfid'];
$sql5 = "select * from class where id = '$classid'";
$result5 = mysql_query($sql5) or die(mysql_error());
$row5 = mysql_fetch_assoc($result5);
$class_name = $row5['name'];
//Define the default variables assuming attendance hasn't been taken.
$david = "select * from student where rfid='$studentrfid'";
$davidresult = mysql_query($david) or die(mysql_error());
$drow = mysql_fetch_assoc($davidresult);
if (($drow['excused'] == '1') && ($drow['excuseddate'] == $date)) {
//if($drow['excuseddate'] == $date;
$excusedabsense = '<option value="Excused Absense" label="Excused Absense" selected="selected">Excused Absense</option>';
} else {
$excusedabsense = '';
}
$presentpunctual = '<option value="Present" label="Present">Present</option>';
$presenttardy = '<option value="Tardy" label="Tardy">Tardy</option>';
$unexcusedabsense = '<option value="Absent" label="Absent">Absent</option>';
if (isset($_POST['editdate'])) {
$date = $_POST['date'];
}
$realfname = $studentfname;
$reallname = $studentlname;
$sql4 = "select * from attendance_main where StudentID = '$studentrfid' AND date = '$date' AND classID = '$class_name'";
$result4 = mysql_query($sql4) or die(mysql_error());
$row4 = mysql_fetch_assoc($result4);
if ($row4['status'] == "Present") {
$presentpunctual = '<option value="Present" label="Present" selected="selected">Present</option>';
} else {
$presentpunctual = '<option value="Present" label="Present">Present</option>';
}
if ($row4['status'] == "Tardy") {
$presenttardy = '<option value="Tardy" label="Tardy" selected="selected">Tardy</option>';
} else {
$presenttardy = '<option value="Tardy" label="Tardy">Tardy</option>';
}
if ($row4['status'] == "Absent") {
$unexcusedabsense = '<option value="Absent" label="Absent" selected="selected">Absent</option>';
} else {
$unexcusedabsense = '<option value="Absent" label="Absent">Absent</option>';
}
$b++;
echo "<tr>";
if (!isset($dateform)) {
$dateform = date('m/d/Y');
}
$date = date('m/d/Y');
echo '<td><iframe src="flag.php?&flagdate=' . $dateform . '&curdate=' . $date . '&class=' . $classid . '&flag=1&user=' . $studentrfid . '&curflag=' . $realrfid['flag'] . '&flagclass=' . $classname . '" width="50" height="30" frameborder="0" scrolling="no"> </iframe></td>';
//Yesterday
$sql8 = "select * from attendance_main where StudentID = '$studentrfid' AND date='$yesterdaysql' AND classID = '$class_name'";
$result8 = mysql_query($sql8) or die(mysql_error());
$tooltiprow = mysql_fetch_assoc($result8);
if (mysql_num_rows($result8) == 0) {
$tooltipresult_yesterday = "N/A";
} else {
$tooltipresult_yesterday = $tooltiprow['status'];
}
//2 days
$sql8 = "select * from attendance_main where StudentID = '$studentrfid' AND date='$days2sql' AND classID = '$classid'";
$result8 = mysql_query($sql8) or die(mysql_error());
$tooltiprow = mysql_fetch_assoc($result8);
if (mysql_num_rows($result8) == 0) {
$tooltipresult_2days = "N/A";
} else {
$tooltipresult_2days = $tooltiprow['status'];
}
//3 days
$sql8 = "select * from attendance_main where StudentID = '$studentrfid' AND date='$days3sql' AND classID = '$class_name'";
$result8 = mysql_query($sql8) or die(mysql_error());
$tooltiprow = mysql_fetch_assoc($result8);
if (mysql_num_rows($result8) == 0) {
$tooltipresult_3days = "N/A";
} else {
$tooltipresult_3days = $tooltiprow['status'];
}
$tooltip = "<b>" . $yesterday . ":</b> " . $tooltipresult_yesterday . " - <b>" . $days2 . ":</b> " . $tooltipresult_2days . " - <b>" . $days3 . ":</b> " . $tooltipresult_3days;
echo "
<!-- Loop #" . $b . " --> <td><a href='#'";
?> onMouseover="ddrivetip('<?php
echo $tooltip;
?>')"; onMouseout="hideddrivetip()"> <?php
echo $realfname . " " . $reallname . "</a></td>";
echo '<td>
<select name="status' . $b . '">
' . $presentpunctual . '
' . $presenttardy . '
' . $excusedabsense . '
' . $unexcusedabsense . '
</select>
' . $hiddenfield . '
<input type="hidden" name="i" value="' . $b . '" />
<input type="hidden" name="studentid' . $b . '" value="' . $studentrfid . '">
<input type="hidden" name="classid" value="' . $class_name . '"></td>
<td><input type="text" name="comments' . $b . '" size="40" /></td></tr>
<!-- End Loop -->';
}
}
}
It essentially prints out student name and a drop down of statuses (if attendance was taken that day, the status will be whatever is set in the database). The date, flag, and tooltip functions are extra additions. (Date is for previous days, tooltip shows previous attendance on hover)
This data is being executed through the following loop:
if (isset($_GET['update'])) {
mysql_query("UPDATE teacher_accounts SET attendance = '1' WHERE username = '$username'") or die(mysql_error());
$error = 0;
$limit = $_GET['i'];
$starter = 0;
$num = 0;
while ($starter < $limit) {
$num++;
$statusinc = "status" . $num;
$studentinc = "studentid" . $num;
$commentsinc = "comments" . $num;
$starter++;
$studentID = $_GET[$studentinc];
$status = $_GET[$statusinc];
$comments = $_GET[$commentsinc];
$date = date("m/d/Y");
$sql = "select * from student where id = '$studentID'";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($result);
$classid = $_GET['classid'];
if (isset($_GET['dateedit'])) {
$date = $_GET['dateedit'];
$count = "select * from attendance_main where StudentID = '$studentID' AND date = '$date' AND classID='$classid'";
$cresult = mysql_query($count) or die(mysql_error());
if (mysql_num_rows($cresult) > 0) {
$sql = "UPDATE attendance_main SET status='$status',comments='$comments',date='$date',classID='$classid' where StudentID = '$studentID'";
} else {
$sql = "INSERT INTO attendance_main (StudentID,status,comments,date,classID) VALUES ('$studentID','$status','$comments','$date','$classid')";
}
if (mysql_query($sql)) {
$return = "<h3>Successfully updated the attendance.</h3>";
}
} else {
$count = "select * from attendance_main where StudentID = '$studentID' AND date = '$date' AND classID='$classid'";
$cresult = mysql_query($count) or die(mysql_error());
if (mysql_num_rows($cresult) > 0) {
$sql = "UPDATE attendance_main SET status='$status',comments='$comments',date='$date',classID='$classid' where StudentID = '$studentID'";
if (mysql_query($sql)) {
$return = "<h3>Successfully updated the attendance for " . $num . " students.</h3>";
}
} else {
$sql = "INSERT INTO attendance_main (StudentID,status,comments,date,classID) VALUES ('$studentID','$status','$comments','$date','$classid')";
if (mysql_query($sql)) {
$return = "<h3>Successfully inserted today's attendance for " . $num . " students.";
}
}
}
}
echo $return;
For some reason, data is sometimes not being inserted properly. For example, a teacher might submit attendance on 02/08/2011, for a specific class, and certain students might appear twice under that attendance. This shouldn't be the case according to the code, because it should first check if they exist and, if they do, update the record rather than insert.
I've also seen cases where records are randomly deleted altogether. When a teacher takes attendance, all statuses are automatically set to Present. However, when I searched records on a certain date in the database, 2 students were missing records (which isn't even possible unless its being deleted)
Anyone have any idea why this might happen? I've tried replicating it myself (by repeatedly submitting the form, refreshing the page after it's processed, etc, to no avail.)
Thank you for the help!
Your query that check if a record exists is looking for all 3. 1) $studentID, 2) $classid and 3) $classid However the UPDATE statement is just looking for $studentID.
I would suggest you create a PRIMARY KEY (or UNIQUE INDEX) on StudentID,date,classID, then use the MySql INSERT ON DUPLICATE KEY UPDATE...
INSERT INTO attendance_main (StudentID,status,comments,date,classID)
VALUES ('$studentID','$status','$comments','$date','$classid')
ON DUPLICATE KEY UPDATE
status = VALUES(status),
comments = VALUES(comments)
Don't forget to sanitize the database input by using mysql_real_escape_string for example $status = mysql_real_escape_string($_GET[$statusinc]);.

Problems with certain characters in jQuery/PHP

I am having problems with some characters after I added some jQuery to my code.
http://www.blueskycouncil.com/login-form.php (login: stack/this)
It worked fine when I was just doing it all in php but now it converts some of the characters weirdly.
This is the jQuery code I am using:
<script type="text/javascript">
// Check to see if document is ready
$(document).ready(function () {
// Set sort mode to Best
$.post("_db_index.php",
{sort_id: "best"},
// Take data from _db_index.php and put it into the HTML
function(output){
$('#left').html(output).show();
});
});
// Check to see whether user have voted on item before
function updateKarma(element, id, sortId){
$.post("idea_karma.php",
{pagetype: "index", karmatype: "ideaspace", id: id, sort_id: sortId},
function(output){
element.parentNode.className="karma-btn_voted";
element.parentNode.innerHTML="<span class=\"voted\">"+output+"</span>";
});
return false;
}
function viewMode(sortId){
$.post("_db_index.php",
{sort_id: sortId},
function(output){
$('#left').html(output).show();
$.post("subnavigation.php",
{sort_id: sortId},
function(output){
$('#base').html(output).show();
});
});
};
$(function(){
$(".base a").hover(function(){
$(this).children("span").fadeOut();
}, function(){
$(this).children("span").fadeIn();
})
});
and in the _db_index.php file it fetch it like this
<?php
// Start session
require_once('auth.php');
require_once('config.php');
require_once('db_open_select.php');
// Functions
include('trunctate_text.php');
$sort_id = $_POST['sort_id'];
$member_id = $_SESSION['SESS_MEMBER_ID'];
// Check for PHP Insert Hack
if(array_key_exists("sort_id",$_POST)){
$sort_allowed = array("best","new","comments");
if(in_array($_POST["sort_id"],$sort_allowed)){
$sort_id = $_POST["sort_id"];
}
}
echo "<div id=\"gradient\">";
//If User selected Best Rated or if url is empty:
if (empty($_POST) OR $sort_id == "best") {
//Perform database query
$result = mysql_query("SELECT * , (SELECT COUNT( 1 ) FROM comments C WHERE C.idea_id = I.id) AS COMMENTS, ( SELECT login FROM members M WHERE I.member_id = M.member_id ) as login FROM ideaspace I ORDER BY KARMA DESC", $connection);
$query = mysql_query("SELECT idea_id FROM vote_idea WHERE member_id = $member_id", $connection);
//Create array with which ideas the current user has voted on already
$user_voted_on_this = array();
while($row = mysql_fetch_assoc($query))
{
$user_voted_on_this[] = $row["idea_id"];
}
//If User selected newest:
} elseif ($sort_id == "new") {
$result = mysql_query("SELECT * , (SELECT COUNT( 1 ) FROM comments C WHERE C.idea_id = I.id) AS COMMENTS, ( SELECT login FROM members M WHERE I.member_id = M.member_id ) as login FROM ideaspace I ORDER BY DATE DESC", $connection);
$query = mysql_query("SELECT idea_id FROM vote_idea WHERE member_id = $member_id", $connection);
//Create array with which ideas the current user has voted on already
$user_voted_on_this = array();
while($row = mysql_fetch_assoc($query))
{
$user_voted_on_this[] = $row["idea_id"];
}
//If User selected most commented:
} else {
if ($sort_id == "comments")
$result = mysql_query("SELECT * , (SELECT COUNT( 1 ) FROM comments C WHERE C.idea_id = I.id) AS COMMENTS, ( SELECT login FROM members M WHERE I.member_id = M.member_id ) as login FROM ideaspace I ORDER BY COMMENTS DESC", $connection);
$query = mysql_query("SELECT idea_id FROM vote_idea WHERE member_id = $member_id", $connection);
$user_voted_on_this = array();
while($row = mysql_fetch_assoc($query))
{
$user_voted_on_this[] = $row["idea_id"];
}
}
if (!$result && !$query) {
die("Database connection failed: " . mysql_error());
}
// 4. Use data from database
while ($row = mysql_fetch_array($result)) {
echo
"<dt id=\"idea\">";
if (in_array($row['id'],$user_voted_on_this)) {
echo
"<div class=\"karma-btn_voted\">
<span class=\"voted\">{$row['karma']}</span>
</div>";
} else {
echo
"<div class=\"karma-btn\">
<img src=\"images/btn_lrg_karma.png\" alt=\"Alternative text\"><span class=\"voted\"><div class=\"newkarma\">{$row['karma']}</div></span>
</div>";
}
echo
"<div class=\"textbox\">
<P class=\"category\">" . $row['category'] . "</p>
<P class=\"headline\"> " . $row['d_header']."</P>
<P>" . $shortdesc = myTruncate($row['d_description'], 220, " ") . "</p>" .
"<P class=\"name\">Submitted by " . $row['login'] . " " . date('D d Y', strtotime($row['date'])) . "<img src=\"images/comments.png\" align=\"center\">". $row['COMMENTS'] ."</p>" .
"</div>
</dt></div>";
}
?>
<?Php
require_once('db_close.php');
?>
As I said it worked fine when it was PHP but now that i fetch the data it replaces some characters with diamond ? character icon.
is an encoding issue, lots of things to check - UTF-8 problem when saving to mysql
The response is encoded in cp1252, but your page in UTF8
The char that disappears has decimal-code 146
’
You should change the encoding before you send the response(or better before you insert the data to the db).
mb_convert_encoding($str, "UTF-8", "CP1252");
Thanks everyone I fixed it
mysql_query("SET NAMES utf8"); in the db_connection file.

mysql error in php

i'm trying to run this php code which should display a quote from mysql, but can't figure out where is it going wrong. the result variable is null or empty. can someone help me out. thanks!
<?php
include 'config.php';
// 'text' is the name of your table that contains
// the information you want to pull from
$rowcount = mysql_query("select count(*) as rows from quotes");
// Gets the total number of items pulled from database.
while ($row = mysql_fetch_assoc($rowcount))
{
$max = $row["rows"];
//print_r ($max);
}
// Selects an item's index at random
$rand = rand(1,$max)-1;
print_r ($rand);
$result = mysql_query("select * from quotes limit $rand, 1") or die ('Error: '.mysql_error());
if (!$result or mysql_num_rows($result))
{
echo "Empty";
}
else{
while ($row = mysql_fetch_array($result)) {
$randomOutput = $row['cQuotes'];
echo '<p>' . $randomOutput . '</p>';
}
}
$result = mysql_query("SELECT * FROM quotes ORDER BY rand() LIMIT 1") or die ('Error: '.mysql_error());
if (!$result || mysql_num_rows($result) == 0)
echo "Empty";
else {
while ($row = mysql_fetch_array($result)) {
$randomOutput = $row['cQuotes'];
echo '<p>' . $randomOutput . '</p>';
}
}
// your script probably can't go on without this file?
require 'config.php';
// I prefer to always pass the connection resource to mysql_query/mysql_real_escape_string
// assume $mysql = mysql_connect....
$result = mysql_query("SELECT Count(*) AS rows FROM quotes", $mysql)
or die(mysql_error());
// there's only one row with only one column, so mysql_result() is fine
$rowcount = mysql_result($result, 0, 0);
$rand = rand(0,$rowcount-1);
$result = mysql_query("SELECT cQuotes FROM quotes LIMIT $rand, 1", $mysql)
or die ('Error: '.mysql_error());
// there's either one or zero records. Again, no need for a while loop
$row = mysql_fetch_array($result, MYSQL_ASSOC);
if ( !$row ) {
echo "Empty";
}
else{
// do you have to treat $row['cQuotes'] with htmlspecialchars()?
echo '<p>', $row['cQuotes'], '</p>';
}
if ($result && mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
$randomOutput = $row['cQuotes'];
echo '<p>' . $randomOutput . '</p>';
}
} else {
echo "Empty";
}

Categories