How to select random value from mysql database? - php

I want make "daily tip" to my website but i don't know how. I think i can use PHP and mysql database but how i can make it? Or can i make example .txt file and some php function choose dailytip from .txt file? I alredy tried this code:
Iam making website which shows daily tip to user. How I can select random value from database.
Here is what I tried:
<?php
function random_tip()
{
$link = mysql_connect ("host", "user","pass", "a2955851_SW")
or die("Error " . mysql_error($link));
mysql_select_db("a2955851_SW");
$sql = "SELECT * FROM `randomtip` ORDER BY RAND() LIMIT 1()";
$row = mysql_query($sql, $link)
or die("Error: ".mysql_error($link));
mysql_free_result($row);
mysql_close($link);
return ($row['tip']);
}
?>

$row = mysql_query($sql, $link)
^^^--- statement handle
return ($row['tip']);
^^^^^^^--- using statement handle as if it was a row of results
You should have
$result = msyql_query(...);
$row = mysql_fetch_assoc($result);
echo $row['tip'];
instead
Note that the mysql_*() functions are obsolete/deprecated, and should not be used in any new code.

Related

Empty MySQL query result not working as expected?

I am using the following script to check a code, so when the user enters the survey code they get the survey that is associated with that code. The part that fetches the survey is working as its supposed to, but I cant seem to get the error message to come up for some reason. If I enter a wrong code or no code all on the form this posts from, all I get is a blank page.
<?php
$con = mysql_connect("myhost","myuser","mypassword;
if (!$con) {
die('Could not connect: ' . mysql_error());
}
// Select mysql db
mysql_select_db("mydb", $con);
$questionaireID = $_POST['questionaireID'];
$result = mysql_query("SELECT * FROM itsnb_questionaire WHERE questionaireID='$questionaireID'") or die(mysql_error());
while($row = mysql_fetch_array($result)) {
if (empty($row['questionaireID'])) {
echo '<h2>Sorry I cant find a quiz with that code, please recheck your code.</h2>';
} else {
$url = $row['questionaireurl'];
header('Location: '.$url.'');
}
}
?>
It will never get there, because if the resultset is empty, it'll skip the while loop.
Try this, instead, limiting to 1 record (which is what you expect) and using an if...else instead of your while (while is only required when multiple results are expected):
$sql = "SELECT *
FROM itsnb_questionaire
WHERE questionaireID = '{$questionaireID}'
LIMIT 1";
$result = mysql_query($sql) or die(mysql_error());
if ($row = mysql_fetch_array($result)) {
$url = $row['questionaireurl'];
header('Location: '.$url.'');
} else {
echo '<h2>Sorry I cant find a quiz with that code, please recheck your code.</h2>';
}
If number of returned rows is zero than you haven't found your result therefore you can display apropriate error message
try
if (mysql_num_rows($result)<1){
//error
}

Display MySQL Database as an array

I have a MySQL database full of user information, like their username, password, email, etc.
I want a PHP script that allows me to pull JUST their username and display it like so:
"username1","username2","username3"
Literally exactly like that, the quotes and all.
EDIT: Sorry for not supplying enough information.
The table is named "users" the field I want to pull off it is "username" I can get it to pull and display all the information, my only problem is imploding it.
OK dude, read the comments
<?php // open a php tag
$dbc = mysql_connect("host", "username", "password"); // connect to database
mysql_select_db("db_name", $dbc) // select the database
$sql = "SELECT `username` FROM `users_table`"; // select only the username field from the table "users_table"
$result = mysql_query($sql); // process the query
$username_array = array(); // start an array
while($row = mysql_fetch_array($result)){ // cycle through each record returned
$username_array[] = "\"".$row['username']."\""; // get the username field and add to the array above with surrounding quotes
}
$username_string = implode(",", $username_array); // implode the array to "stick together" all the usernames with a comma inbetween each
echo $username_string; // output the string to the display
?>
I've seen all the other answers, however have you considered using PDO instead of mysql_query functions? It's a much nicer way to work with the database.
Here's what you want to achieve in a few lines of code (using lamba functions):
$dbh = new PDO("mysql:host=localhost;dbname=test", "yourusername", "yourpassword");
$results = $dbh->prepare("SELECT u.username FROM users u");
$results->execute();
$results = $results->fetchAll();
echo implode(", ", array_map(function(&$r) { return $r['username']; }, $results));
Output: Jamie, Bob, Chris
Nice and clean. Also, you should check if you have any results that have been returned and if the query was successful.
Just another approach.
EDIT: I've just realised you're a beginner so my answer may be a bit too advanced. However, i'll leave it for others to see as a solution, and perhaps you might look into using PDO an lamba functions when you learn a bit more. Best of luck.
Let's assume that you have a 'mydb' database and 'users' table in it.
SQL needed:
USE mydb;
SELECT username from users;
Short version:
Wrap it in PHP calls to mysql PHP library
Get result as an array then implode it with comma symbol.
Long version:
First we need to connect to database:
$db = mysql_connect('DATABASE_HOST', 'USER', 'PASSWORD');
if (!$db) {
die('Not connected : ' . mysql_error());
}
$db_selected = mysql_select_db('mydb', $db);
if (!$db_selected) {
die ('Can\'t use mydb: ' . mysql_error());
}
Remember to always check the return values of functions.
Then we query the database:
$result = mysql_query('select username from users', $db);
...and fetch results in flat array (we need only usernames):
while ($row = mysql_fetch_array($result, MYSQLI_ASSOC))
{
$data[] = $row['login'];
}
Then we format the returned data according to your specs:
$string_result = '"'. implode('", "', $data) . '"';
You can do with $string_result anything you want, just close the database connection immediately after use:
mysql_close($db);
Good luck with learning PHP, BTW. ;)
You could using PHP's implode, but it's probably easier just do it in SQL assuming that the list won't be too long:
SELECT GROUP_CONCAT(CONCAT('"', username, '"')) AS usernames
FROM your_table

Php Custom Function For Mysql Query Not Working

I have created two functions one for connecting to MySQL database and one for running a specific query.
I enter the database name as parameter for first function to connect to the database, this works fine, but my problem is with the second one.
2nd function returns the $result from running a query, but when I use mysql_fetch_array with the $result, it gives one output even if it supposed to give more than one.
As I am no php expert so i can't find the solution. Please help me.
Here is the code:
File Function.php
<?php
function myconnect($data)
{
$db_host='localhost';
$db_user='root';
$db_pwd='';
$data=$data;
$dbc = mysqli_connect($db_host, $db_user,$db_pwd,$data) or die (mysql_error());
return $dbc;
}
function runquery($db,$table,$tcol,$tid)//(databse,table,column_name,identifier)
{
$dbc=myconnect($db);
$query="SELECT *FROM ".$table." WHERE ".$tcol."=".$tid." ORDER BY first_name ASC";
$result = mysqli_query($dbc, $query);
return $result;
}
?>
File test.php
<?php
require_once('testfunc.php');
$result= runquery('user','user_basic','user_type','1');
//runquery('database','table','col','id')/
while($row=mysqli_fetch_array($result))
{
echo '<strong>First Name:</strong>' . $row['first_name'] . '<br/>';
}
?>
If I am doing all wrong then suggest me a better way :-)
A quick glance shows that in your function runquery
SELECT *FROM
should be
SELECT * FROM
note the space after the *
EDIT :
I also notice you are using *mysqli_fetch_array* and this is not a valid mysqli method. You are right in using the mysqli extension over mysql but you should look more into statement fetch to solve this issue. The link I provided give a procedural example that should work for what you need.
function myconnect($db)
{
/*Removed redundant - single use variables*/
/*DB name was passed to the client_flags parameter of mysql_connect instead of mysql_select_db*/
$dbc = mysql_connect("localhost", "root","") or die (mysql_error());
/*Inserted Line*/
mysql_select_db($data);
return $dbc;
}
Currently you're not selecting a database - equivalent of USE DATABASE db_name.
Couple of syntax changes and function definition
function runquery($db,$table,$tcol,$tid)//(databse,table,column_name,identifier)
{
$dbc=myconnect($db);
/*Query and link identifier were in the wrong order*/
return mysql_query("SELECT * FROM ".$table." WHERE ".$tcol."=".$tid." ORDER BY first_name ASC", $doc);
}
Finally a couple of syntax changes, function calls
require_once('testfunc.php');
$result= runquery('user','user_basic','user_type','1');
/*fetch associateive array of result during iteration*/
while($row=mysql_fetch_assoc($result))
{
echo '<strong>First Name:</strong>' . $row['first_name'] . '<br/>';
}

Add MySQL result into PHP array

I would like to add results into array and print on screen.
Here's my code and nothing is printing...could someone help me take a look.
include('config.php');
$con = mysql_connect($host, $username, $password);
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db('members', $con) or die(mysql_error()) ;
$sql = "SELECT * FROM people where status like '%married%' ";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)){
$result_array[] = $row['id']; // <-------**here**
}
return $result_array;
echo($result_array);
mysql_close($con);
You're doing a return before you do the echo/mysql_close, so the echo/close calls never get executed. Unless you've got more code around this snippet, there's no point in having that return call, as you're not actually in a function, so the return is effectively acting as an "exit()" call, since you're already at the top of the execution stack.
Firstly, change:
mysql_select_db(mtar, $con) or die(mysql_error());
To:
mysql_select_db('mtar', $con) or die(mysql_error());
Then remove return $result_array; - you don't need it and when used outside of a function it just halts execution of the script.
Finally, change
echo($result_array);
to:
print_r($result_array);
EDIT: Some additional thoughts:
You don't need parentheses around the argument to echo - it's actually more efficient to leave them out: echo $var; is quicker than echo($var);
If you're only ever going to use the id column, then don't select the whole row: use SELECT id FROM instead of SELECT * FROM.
Are you sure you need the wildcards either side of "married"? You may well do (depends on what the possible values of status are), but you probably don't. So
$sql = "SELECT id FROM people where status = 'married' ";
May be better,

Why is my php script freezing?

What is causing my php code to freeze? I know it's cause of the while loop, but I have $max_threads--; at the end so it shouldn't do that.
<html>
<head>
<?php
$db = mysql_connect("host","name","pass") or die("Can't connect to host");
mysql_select_db("dbname",$db) or die("Can't connect to DB");
$sql_result = mysql_query("SELECT MAX(Thread) FROM test_posts", $db);
$rs = mysql_fetch_row($sql_result);
$max_threads = $rs[0];
$board = $_GET['board'];
?>
</head>
<body>
<?php
While($max_threads >= 0)
{
$sql_result = mysql_query("SELECT MIN(ID) FROM test_posts WHERE Thread=".$max_threads."", $db);
$rs = mysql_fetch_row($sql_result);
$sql_result = mysql_query("SELECT post FROM test_posts WHERE ID=".$rs[0]."", $db);
$post = mysql_fetch_row($sql_result);
$sql_result = mysql_query("SELECT name FROM test_posts WHERE ID=".$rs[0]."", $db);
$name = mysql_fetch_row($sql_result);
$sql_result = mysql_query("SELECT trip FROM test_posts WHERE ID=".$rs[0]."", $db);
$trip = mysql_fetch_row($sql_result);
if(!empty($post))
echo'<div class="postbox"><h4>'.$name[0].'['.$trip[0].']</h4><hr />' . $post[0] . '<br /><hr />[Reply]</div>';
$max_threads--;
}
?>
</body>
</html>
First, I'd suggest completely getting rid of the extraneous HTML bits. Then, build up your code slowly, line-by-line to see if you can find the offending line. So write a script that just connects to the database and see what happens.
If you find for example that this code...
<?php
$db = mysql_connect("host","name","pass") or die("Can't connect to host");
mysql_select_db("dbname",$db) or die("Can't connect to DB");
?>
...is causing the freeze on its own, then it could easily be a problem with the MySQL server.
However, if the browser itself is crashing, that sounds like an issue with your system rather than something that PHP or MySQL is doing...
Try this 1 SQL query instead of those 1 + (4 * n) queries:
SELECT MIN(ID), post, name, trip FROM test_posts GROUP BY Thread
Maybe a LIMIT 50 (or whatever max # of threads to return) at the end as well, that could be a lot of data.
You can just loop over the results of this query instead of $max_threads and all the extra db calls, via while ($row = mysql_fetch_row($sql_result)) { /* echo(...); */ }.
Not sure that's exactly the same as what you're trying to fetch without knowing more about the data (getting the root post of each thread in a forum?), but it should be pretty close.
(P.S.: if that's a threaded 2ch-style forum deal, I'm not sure that's an ideal db design. A parent-child adjacency list might be better than maintaining a number count for each thread. Just a guess though.)
I'm thinking it's because you're hitting the sql database 4 times per loop. Is there any way you can maybe access it all at once, and then parse the incoming data from there?
$dbsql = 'SELECT * FROM my_database';
$result = mysql_query($dbsql);
while($row = mysql_fetch_array($result)) {
// Parse information here, rather than
// accessing the database for individual variables...
}
Something like that.
Update:
Other than what I've already said (and you've dismissed) all I see are some here & there coding quirks:
This part didn't have a space between echo and the string. The 'hr' element didn't have a starting bracket.
echo '<div class="postbox"><h4>'.$name[0].'['.$trip[0].']</h4><hr>' . $post[0] . '<br /><hr />[Reply]</div>';
'while' Shouldn't be capitalized.
while($max_threads >= 0)
Again, clean code is a good place to start, but that's all I've got, personally. I just recently cleaned up my own site, which was crashing IE (and no other browser), simply because it had too many markup errors. Hope it helps.
Maybe you can scatter calls to this simple function in yer code:
function of($required)
{
$args = func_get_args();
var_dump($args);
ob_flush();
flush();
}
of(__LINE__, $max_threads);
You can also use something like this for your queries:
function mydb_query($query, $db = null)
{
$args = func_get_args();
$result = call_user_func_array('mysql_query', $args);
if (!$result) {
of(array(__FUNCTION__), mysql_error(), $sql);
//return something else?
}
return $result;
}
$result = mydb_query("SELECT post, name, trip FROM test_posts WHERE ID = (SELECT MIN(ID) FROM test_posts WHERE Thread={$max_threads})", $db);
You should use mysqli/PDO/framework with support for prepared statements.
Probably the script is exceeding the maximum server execution time threshold, try this on the top of your file to confirm this:
ini_set('max_execution_time', '180');

Categories