Alright, so I have a database, each with an ID, a name and a textvalue.
I wish to be able to print each of a specific row individually. When I use
$result = mysql_query("SELECT * FROM mytable", $db);
$row = mysql_fetch_array($result);
echo $row['text'];
I am only able to print the first row, as it doesn't select any specifics. The problem is, I'm not sure how to use the WHERE ID='X', as I want the first one to print the first column, the second to print the second column and so forth (there are a total of 13 lines). I want to echo them on different places on the page, so just calling everything at once is not what I'm looking for.
The way things are now, I'll have to use the code above for each time I want to print it, and manually edit the WHERE ID='1' on the first print, the second to WHERE ID='2' and so on, which is rather a pain in the ass.
Any suggestions is appreciated.
Keep calling mysql_fetch_array until it returns null:
while($row = mysql_fetch_array($result ))
{
echo $row['text'] . '<br/>';
}
This is shown in the documentation, which also will tell you this:
Warning
This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:
Here's an example using a more object-oriented approach:
1) setup a PDO object like this:
$dbhost = '127.0.0.1';
$dbuser = 'yourDbUsername';
$dbpass = 'yourDbPassword';
$dbname = 'databaseName';
$dsn = 'mysql:host=' . $dbhost . ';dbname=' . $dbname;
$dbAdapter = new PDO($dsn,$dbuser,$dbpass);
$dbAdapter->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$dbAdapter->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
2) use PDO objects to run queries and fetch result sets:
$sql = 'SELECT * FROM mytable';
$statementObject = $dbAdapter->query($sql);
$resultSet = $statementObject->fetchAll();
3) iterate over the resulting array:
foreach($resultSet as $row){
echo $row['text'] . "<br />";
}
This is how to iterate through all records.
$result = mysql_query("SELECT text FROM mytable", $db);
while ( $row = mysql_fetch_array($result) ) {
echo $row['text'];
}
$i = 1;
$result = mysql_query("SELECT text FROM mytable WHERE ID > 0 AND ID < 5", $db);
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
echo $i . ' - ' . $row[0] . '<br/>';
$i++
}
If you want 4 variables with the text to use in differents part of your code then use:
$result = mysql_query("SELECT text FROM mytable WHERE ID > 0 AND ID < 5", $db);
$var1 = mysql_fetch_array($result, MYSQL_NUM);
echo $var1[0];
$var2 = mysql_fetch_array($result, MYSQL_NUM);
echo $var2[0];
$var3 = mysql_fetch_array($result, MYSQL_NUM);
echo $var3[0];
$var4 = mysql_fetch_array($result, MYSQL_NUM);
echo $var4[0];
Related
I have a polymer(1.0) app i am trying to create (based on stretch-tutorials league table), i cant figure out the routing if use mvc, so i have opted for the one page site, referencing different php files.
I Have a table in MYSql that i trying to incorporate into the table, using a simple echo table script, but this repeats itself hundreds of times. How can i stop this loop ?
$result = mysql_query('select * from results',$connection) or die('cannot show tables');
while($tableName = mysql_fetch_row($result)) {
$sql = ('SELECT `home_team_name`,`away_team_name`,`home_goals_for`, `away_goals_for`, DATE_FORMAT(`fixture_date`, "%e %M %Y"), TIME_FORMAT(`fixture_time`, "%h:%i %p") FROM `results` ORDER BY fixture_date desc LIMIT 20 '.$table) or die('cannot show columns from '.$table);
echo '<h3>',$table,'</h3>';
$result2 = mysql_query($sql);
if(mysql_num_rows($result2)) {
echo '<table cellpadding="4" cellspacing="0" class="table table-striped table-hover table-bordered">';
echo '<tr class="info"><th>Home team</th><th>Away Team</th><th>Score</th><th>Score</th><th>Date<th>Time</th></tr>';
while($row2 = mysql_fetch_row($result2)) {
echo '<tr>';
foreach($row2 as $key=>$value) {
echo '<td>',$value,'</td>';
}
echo '</tr>';
}
echo '</table><br />';
}
}
I have added ' < 50 ' but this returns 50 table header rows only ?
the site is live at http://jay-o.uk/#!/results the css and other data are okay for now, just this pesky loop.
Well.. maybe you need this code:
// Create an array
$items = array();
while ($row = mysql_fetch_array($resulting, MYSQL_ASSOC)) {
/* print new insert */
var_dump('new item');
/* add a new item */
$items[] = array(
'home_team_name' => $row['home_team_name'],
'away_team_name' => $row['away_team_name'],
'home_goals_for' => $row['home_goals_for'],
'away_goals_for' => $row['away_goals_for']
);
}
$json_response = json_encode($items);
print $json_response;
If $json_response are a empty array maybe the problem is that the query don't return any row.
You need to set a "LIMIT" in the first query if you want to avoid a timeout operation, also i think that is posible to call a unique query that return all the info that you need but i don't know because your query is unintelligible.
Your code is wrong, the second query don't use the $table variable that is null value and what is de purpose to putting it after the limit parameter?
$results = mysql_query('SELECT * FROM table_name ORDER BY field_name LIMIT 50');
if(mysql_num_rows($results)) {
print '<table>';
while ($row = mysql_fetch_row($results)) {
print '<tr>';
foreach ($row as $field_name => $field_value) print '<td>'.$field_value.'</td>';
print '</tr>'
}
print '</table>';
}
Sorry, the code is a bit messy, ive been working on this for a while and ifs frustrating, im not sure where i am going wrong, if i remove the $tableName variable i get an empty array, no matter what i do this is the results.
I have tried in json to no avail...
$db = mysql_connect($host,$user,$pass);
if (!$db) {
die('Could not connect to db: ' . mysql_error());
}
//Select the Database
mysql_select_db($db_name,$db);
$resulting = mysql_query("select * from results", $db);
//Create an array
$json_response = array();
while ($row = mysql_fetch_array($resulting, MYSQL_ASSOC)) {
$row_array['home_team_name'] = $row['home_team_name'];
$row_array['away_team_name'] = $row['away_team_name'];
$row_array['home_goals_for'] = $row['home_goals_for'];
$row_array['away_goals_for'] = $row['away_goals_for'];
//push the values in the array
array_push($json_response,$row_array);
$json = json_encode($json_response);
//echo $json;
$json_result = print_r((array) json_decode($json,true));
echo $json_result;
}
which leaves this: jay-o.uk/config/config.php
Could this be because i am referring to a view in mySql rather than a table ?
How about a simpler solution, just limit the query from the database to 1:
$results = mysql_query('SELECT * FROM table_name ORDER BY field_name LIMIT 1');
I'm trying to assign a field called 'uniqueid' to each row present in my database. There are roughly 188,000 rows available.
Here is the code I am using:
$connection = mysql_connect("localhost","root","root");
mysql_select_db("comics",$connection) or die ("Database not found");
$query = mysql_query("select * from comic_issues");
if ($query){
$rows = mysql_num_rows($query);
foreach($rows as $row){
$str = strtolower($row['series'].$row['volume'].$row['issue']);
$str = preg_replace('/[^A-Za-z0-9]/', '', $str);
$update = "update comic_issues set uniqueid='" . $str . "' where id='" . $row['ID'] . "'";
mysql_query($update);
exit();
}
}
What is happening is that every row gets updated with the same uniqueid, which seems to be a different value each time I run the script.
Instead of
foreach($rows as $row){
you need to do
while ($row = mysql_fetch_row($query)) {
In your code $rows is a number and not an array, therefore you can't do a foreach on it.
Just let MySQL do it all for you:
UPDATE comic_issues SET uniqueid = LOWER(CONCAT(series,volume,issue))
If you must also strip all non-alphanumeric characters, you can either write a stored function or else use a UDF.
I'm a PHP and MySQL newbie trying to write a simple query against a table consisting of 2 columns: one with a text string and the second with a date string. The code below returns the first column (the text string) but not the second date string:
<?php
$link = mysql_connect('localhost', 'myuser', 'mypassword');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('archive')or die("cannot select db");
$string = $_POST['keywords'];
$search_query = "SELECT text, date_written FROM archive_table WHERE text LIKE '%$string%'";
$result = mysql_query($search_query,$link);
$rows = mysql_num_rows($result);
if ($rows == 0) {
echo "sorry, I haven’t written about ".$string." yet.";
}
$count = 0;
while ($count < $rows) {
echo mysql_result($result, $count);
echo "\n\n";
$count = $count + 1;
}
mysql_close($link);
?>
I've tried the following code to replace "echo mysql_result($result, $count);", but it returns nothing at all:
echo mysql_result($result['text'], $result['date_written'], $count);
I'm hoping it's a fairly simple syntax blunder that is easily fixed. Thanks in advance!
Don't use the mysql_* functions, as they're deprecated and not safe. Use either MySQLi or PDO
You also need to fetch your results:
$query = "blah"
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)) {
echo "{$row['text']}, {$row['date_written]}";
}
I'm pretty sure this
echo mysql_result($result['haiku_text'], $result['date_written'], $count);
should be
echo mysql_result($result['text'], $result['date_written'], $count);
You have a prefix in front of the text field but it doesn't have one when you select it.
This is a part of my code, and the echo is to test the value and it gives me Resource ID #5
$id = mysql_query("SELECT id FROM users WHERE firstname='$submittedfirstname' AND lastname='$submittedlastname' AND email='$submittedemail'") or die(mysql_error());
$counter = mysql_num_rows($id);
echo $id;
I am just getting into programming, and lately seeing lot of Resource ID outputs/errors while working with Databases.
Can someone correct the error in my code? And explain me why it isnt giving me the required output?
This is not an error. This is similar to when you try to print an array without specifying an index, and only the string "Array" is printed. You can access the actual data contained within that resources (which you can think of as a collection of data) using functions like mysql_fetch_array().
In fact, if there were an error here, the value of $id would not be a resource. I usually use the is_resource() function to verify that everything is alright before using variables which are supposed to contain a resource.
I guess what you intend to do is this:
$result = mysql_query("SELECT id FROM users WHERE firstname='$submittedfirstname' AND lastname='$submittedlastname' AND email='$submittedemail'") or die(mysql_error());
if(is_resource($result) and mysql_num_rows($result)>0){
$row = mysql_fetch_array($result);
echo $row["id"];
}
Did you mean to echo $counter? $id is a resource because mysql_query() returns a resource.
If you are trying to get the value of the id column from the query, you want to use e.g., mysql_fetch_array().
Here is an excerpt from http://php.net/mysql.examples-basic:
$query = 'SELECT * FROM my_table';
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
// Printing results in HTML
echo "<table>\n";
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "\t<tr>\n";
foreach ($line as $col_value) {
echo "\t\t<td>$col_value</td>\n";
}
echo "\t</tr>\n";
}
echo "</table>\n";
Adapted to the code you provided, it might look something like this:
$result =
mysql_query("SELECT id FROM users WHERE firstname='$submittedfirstname' AND lastname='$submittedlastname' AND email='$submittedemail' LIMIT 1")
or die(mysql_error());
if( $row = mysql_fetch_array($result, MYSQL_ASSOC) )
{
$id = $row['id'];
}
else
{
// No records matched query.
}
Note in my code that I also added LIMIT 1 to the query, as it seems like you are only interested in fetching a single row.
are you looking for
while ($row = mysql_fetch_array($id)) {
echo $row['id'];
}
?
$kode_gel = substr($_GET['gel'],0,3);
$no_gel = substr($_GET['gel'],3,5);
$cek = mysql_query("SELECT id_arisan
FROM arisan WHERE kode_gel = '".$kode_gel."'
AND no_gel = '".$no_gel."'");
$result = mysql_fetch_array($cek);
$id = $result['id_arisan'];
header("location: ../angsuran1_admin.php?id=".$id);
I've been searching for this everywhere, but still can't find a solution: How do I get all the values from a mySQL column and store them in an array?
For eg:
Table Name: Customers
Column names: ID, Name
# of rows: 5
I want to get an array of all the 5 names in this table. How do I go about doing that? I am using PHP, and I was trying to just:
SELECT names FROM Customers
and then use the
mysql_fetch_array
PHP function to store those values in an array.
Here is a simple way to do this using either PDO or mysqli
$stmt = $pdo->prepare("SELECT Column FROM foo");
// careful, without a LIMIT this can take long if your table is huge
$stmt->execute();
$array = $stmt->fetchAll(PDO::FETCH_COLUMN);
print_r($array);
or, using mysqli
$stmt = $mysqli->prepare("SELECT Column FROM foo");
$stmt->execute();
$array = [];
foreach ($stmt->get_result() as $row)
{
$array[] = $row['column'];
}
print_r($array);
Array
(
[0] => 7960
[1] => 7972
[2] => 8028
[3] => 8082
[4] => 8233
)
Note that this answer is outdated! The mysql extension is no longer available out of the box as of PHP7. If you want to use the old mysql functions in PHP7, you will have to compile ext/mysql from PECL. See the other answers for more current solutions.
This would work, see more documentation here :
http://php.net/manual/en/function.mysql-fetch-array.php
$result = mysql_query("SELECT names FROM Customers");
$storeArray = Array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$storeArray[] = $row['names'];
}
// now $storeArray will have all the names.
I would use a mysqli connection to connect to the database. Here is an example:
$connection = new mysqli("127.0.0.1", "username", "password", "database_name", 3306);
The next step is to select the information. In your case I would do:
$query = $connection->query("SELECT `names` FROM `Customers`;");
And finally we make an array from all these names by typing:
$array = Array();
while($result = $query->fetch_assoc()){
$array[] = $result['names'];
}
print_r($array);
So what I've done in this code:
I selected all names from the table using a mysql query. Next I use a while loop to check if the $query has a next value. If so the while loop continues and adds that value to the array '$array'. Else the loop stops. And finally I print the array using the 'print_r' method so you can see it all works. I hope this was helpful.
Since mysql_* are deprecated, so here is the solution using mysqli.
$mysqli = new mysqli('host', 'username', 'password', 'database');
if($mysqli->connect_errno>0)
{
die("Connection to MySQL-server failed!");
}
$resultArr = array();//to store results
//to execute query
$executingFetchQuery = $mysqli->query("SELECT `name` FROM customers WHERE 1");
if($executingFetchQuery)
{
while($arr = $executingFetchQuery->fetch_assoc())
{
$resultArr[] = $arr['name'];//storing values into an array
}
}
print_r($resultArr);//print the rows returned by query, containing specified columns
There is another way to do this using PDO
$db = new PDO('mysql:host=host_name;dbname=db_name', 'username', 'password'); //to establish a connection
//to fetch records
$fetchD = $db->prepare("SELECT `name` FROM customers WHERE 1");
$fetchD->execute();//executing the query
$resultArr = array();//to store results
while($row = $fetchD->fetch())
{
$resultArr[] = $row['name'];
}
print_r($resultArr);
First things is this is only for advanced developers persons Who all are now beginner to php dont use this function if you are using the huge project in core php use this function
function displayAllRecords($serverName, $userName, $password, $databaseName,$sqlQuery='')
{
$databaseConnectionQuery = mysqli_connect($serverName, $userName, $password, $databaseName);
if($databaseConnectionQuery === false)
{
die("ERROR: Could not connect. " . mysqli_connect_error());
return false;
}
$resultQuery = mysqli_query($databaseConnectionQuery,$sqlQuery);
$fetchFields = mysqli_fetch_fields($resultQuery);
$fetchValues = mysqli_fetch_fields($resultQuery);
if (mysqli_num_rows($resultQuery) > 0)
{
echo "<table class='table'>";
echo "<tr>";
foreach ($fetchFields as $fetchedField)
{
echo "<td>";
echo "<b>" . $fetchedField->name . "<b></a>";
echo "</td>";
}
echo "</tr>";
while($totalRows = mysqli_fetch_array($resultQuery))
{
echo "<tr>";
for($eachRecord = 0; $eachRecord < count($fetchValues);$eachRecord++)
{
echo "<td>";
echo $totalRows[$eachRecord];
echo "</td>";
}
echo "<td><a href=''><button>Edit</button></a></td>";
echo "<td><a href=''><button>Delete</button></a></td>";
echo "</tr>";
}
echo "</table>";
}
else
{
echo "No Records Found in";
}
}
All set now Pass the arguments as For Example
$queryStatment = "SELECT * From USERS ";
$testing = displayAllRecords('localhost','root','root#123','email',$queryStatment);
echo $testing;
Here
localhost indicates Name of the host,
root indicates the username for database
root#123 indicates the password for the database
$queryStatment for generating Query
hope it helps
PHP 5 >= 5.5.0, PHP 7
Use array_column on the result array
$column = array_column($result, 'names');
How to put MySQL functions back into PHP 7
Step 1
First get the mysql extension source which was removed in March:
https://github.com/php/php-src/tree/PRE_PHP7_EREG_MYSQL_REMOVALS/ext/mysql
Step 2
Then edit your php.ini
Somewhere either in the “Extensions” section or “MySQL” section, simply add this line:
extension = /usr/local/lib/php/extensions/no-debug-non-zts-20141001/mysql.so
Step 3
Restart PHP and mysql_* functions should now be working again.
Step 4
Turn off all deprecated warnings including them from mysql_*:
error_reporting(E_ALL ^ E_DEPRECATED);
Now Below Code Help You :
$result = mysql_query("SELECT names FROM Customers");
$Data= Array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$Data[] = $row['names'];
}
You can also get all values in column using mysql_fetch_assoc
$result = mysql_query("SELECT names FROM Customers");
$Data= Array();
while ($row = mysql_fetch_assoc($result))
{
$Data[] = $row['names'];
}
This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used.
Reference
YOU CAN USE MYSQLI ALTERNATIVE OF MYSQL EASY WAY
*
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";
$result=mysqli_query($con,$sql);
// Numeric array
$row=mysqli_fetch_array($result,MYSQLI_NUM);
printf ("%s (%s)\n",$row[0],$row[1]);
// Associative array
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
printf ("%s (%s)\n",$row["Lastname"],$row["Age"]);
// Free result set
mysqli_free_result($result);
mysqli_close($con);
?>