Good day,
I'm a noob at PHP and MySQl. Looking to be pointed in the right direction.
I have a MySql table with 5 columns. Each column represents a specific set of data. All numerical.
I want to write PHP code which takes each value in a single column and puts it into an array that I can then modify.
I don't know how to get each column as a separate array. Should I get an array of all the rows and then do something extra to separate each of the 5 numbers in each row into 5 separate arrays?
**
require_once 'login.php';
echo $db;
$conn = mysqli_connect($hn,$un,$pw,$db);
if (!$conn) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
$query = "SELECT xox FROM tablex WHERE id = '1'";
$result = $conn->query($query);
if(!$result) die ("Database access failed: " . $conn->error);
$rows = mysqli_fetch_row($result);
while($rows){
echo $rows['index'];
}
echo $rows[0];
?>
$statement = **yourDatabaseConnection**->query('SELECT column1 FROM table');
$datas = $statement->fetch();
$datas will be an array of your column1 datas
Try reviewing the php documentation, here is a good place to start...php:mysql_fetch_row
Take a look at the example below, if is not what you looking for, please edit your question and provide the approach you are taking (your code) so that we have a better understanding where you are having issues.
<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo $row[0]; // 42
echo $row[1]; // the email value
?>
Related
I've got a problem with fetching data from a MySQL database. It fetches rows, and when printing the result with print_r it looks correct, but when getting one item in the array is always empty, and I don't have a clue why!
If I use phpMyAdmin I can see all rows in the database and they look correct.
Anyone got an idea?
<?php
$con = mysqli_connect($host, $user, $password) or die("Failed to connect to MySQL: " . mysqli_connect_error());;
mysqli_select_db($con, $database) or die("Cannot select DB");
$r = mysqli_query($con, "SELECT Question FROM TempQuestions") or die('Query failed: ' . mysql_error());
Print "Rows ". mysqli_num_rows($r) . "<br>"; // Returns 10 rows
while ($dbResult = mysqli_fetch_array( $r)) {
print_r($dbResult); // Prints the question like Array ([0] => The question in DB, [Question] => The question in DB)
Print "<br><br>";
Print "Question: ";
Print $dbresult['Question']; // Is always empty!
Print $dbresult[0]; // Is always empty!
Print "<br><br>";
}
mysqli_free_result($r);
mysqli_close($con);
?>
... or die('Query failed: ' . mysql_error());
You cannot mix up mysql_* with mysqli_*.
And this should be working now, variable names are case-sensitive:
while ($dbresult = mysqli_fetch_array($r)) {
print_r($dbresult);
Print "<br><br>";
Print "Question: ";
Print $dbresult['Question'];
Print $dbresult[0];
Print "<br><br>";
}
I have the code bellow, it's ok but I want to be able to use for example the 4th value extracted from the database, use it alone, not put all of them in a list, I want to be able to use the values from database individually. How do I echo them?
Edit: I was thinking to simplify things, to be able to add the values from database into one array and then extract the value I need from the array (for example the 4th - ordered by "order_id"). But how?
Right now I can only create a list with all the values one after the other..
(Sorry, I am new to this). Thank you for all your help..
<?php
include '../../h.inc.php';
$con = mysql_connect($db['host'],$db['user'],$db['passwd']);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("database", $con);
$result = mysql_query("SELECT * FROM options WHERE Name LIKE 'x_swift%' ORDER BY order_id");
echo "<table border='1'>
<tr>
<th>Values</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
// echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['VALUE'] . "</td>";
echo "</tr>";
$array = array(mysql_fetch_array($strict));
}
echo "</table>";
mysql_close($con);
?>
To select the value in the value column of the row where order_id is 4, use this SQL:
$query = 'select value from options where order_id = 4';
Then you can access this result in many ways. One is to get the entire result row (which in this case is just one cell) as an associative array:
if ($result = mysql_query($query)) {
$row = mysql_fetch_assoc($result);
echo 'value = ' . $row['value'];
}
You can also get the value directly:
if ($result = mysql_query($query)) {
echo 'value = ' . mysql_result($result, 'value');
}
It would just be a query like...
$result = mysql_query("SELECT * FROM options WHERE ID = 3");
mysql_fetch_row($result);
Unless Im misunderstanding you....let me know
But you really should use PDO, instead of deprecated mysql_* functions
http://php.net/manual/en/book.pdo.php
This is the part of the PHP code I am having the issue:
$query = "SELECT * FROM clients where idcard = '$idcard'";
$result = mysqli_query($dbc, $query)
or die("Error quering database.");
if(mysqli_fetch_array($result) == False) echo "Sorry, no clients found";
while($row = mysqli_fetch_array($result)) {
$list = $row['first_name'] . " " . $row['last_name'] . " " . $row['address'] . " " . $row['town'] . " " . $row['telephone'] . " " . $row['mobile'];
echo "<br />";
echo $list;
}
Even if I insert an existing idcard value I get no output when there is the if statement, an incorrect idcard displays "Sorry, no clients found" fine. However if I remove the if statement if I enter an existing idcard the data displays ok.
Can you let me know what is wrong with the code please ?
Thanks
Use mysqli_num_rows to count the results:
if(mysqli_num_rows($result) == 0) echo "Sorry, no clients found";
mysqli_fetch_array() fetches an item from the database.
This means your if() code fetches a first item from the database.
Then, when you call mysqli_fetch_array() again from the while() condition, the first item has already been fetched, and you are trying to fetch the second one ; which does not exist.
You must ensure that you use the result from mysqli_fetch_array() and not call it one time just for nothing ; or, as an alternative, you could use the mysqli_num_rows() function (quoting) :
Returns the number of rows in the result set.
$query = "SELECT * FROM clients where idcard = '$idcard'";
$result = mysqli_query($dbc, $query)
or die("Error quering database.");
if(mysqli_num_rows($result) == 0) {
echo "Sorry, no clients found";
}else{
while($row = mysqli_fetch_array($result)) {
$list = $row['first_name'] . " " . $row['last_name'] . " " . $row['address'] . " " . $row['town'] . " " . $row['telephone'] . " " . $row['mobile'];
echo $list . "<br />";
}
}
Try this.
EDITED: Added closing bracket.
Use mysqli_num_rows() to test if there is anything returned.
Imagine you put some money in your pocket.
Eventually an idea came to your mind to see if you are still have the money.
You are taking it out and count them. All right.
Still holding them in hand you decided to take them from pocket. Oops! The pocket is empty!
That's your problem.
To see if you got any rows from the database you can use mysqli_num_rows(). It will return the number of bills, without fetching them from the pocket.
The problem is, that you try to use mysqli_fetch_array to queck for the number of results. mysqli_fetch_array will fetch the first result, compare it to false and then discard it. The next mysqli_fetch_array will then fetch the second result, which is not existing.
If you want to check if any clients where found, you can use mysqli_num_rows like this:
$idcard = mysqli_escape_string($dbc, $idcard); // See below: Prevents SQL injection
$query = "SELECT * FROM clients where idcard = '$idcard'";
$result = mysqli_query($dbc, $query) or die("Error quering database.");
if(mysqli_num_rows($result) == 0) {
echo "Sorry, no clients found";
} else {
while($row = mysqli_fetch_array($result)) {
// Do whatever you want
}
}
If $idcard is a user supplied value, please look out for SQL injection attacks.
I'm fairly new to php and mysql and I'm on the home stretch of finishing my page but I've been banging my head on the keyboard all day trying to figure out how to fix this problem. I've set up a php script to run as a cron even every 24 hours. The script assigns a random number between 10 and 30 to each field in my table. That works fine and every time I load the script the values change.
The problem I'm having is when I try to use those values. The result keeps printing as the word Array instead of the number in the table. So I'll give you some snippets of the code I'm running here. This is the cron event.
?php
$con = mysql_connect("localhost","username","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("dbname", $con);
$random= rand(10, 30);
mysql_query("UPDATE winners SET pool= '$random'");
mysql_close($con);
And here is the script to call up the values.
php?
$db = mysql_connect('localhost','username','pass') or die("Database error");
mysql_select_db('dbname', $db);
$query = "SELECT pool FROM winners";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result))
if ( $row % 2 )
{
echo "<h4>Result 1</h4>";
echo "$row";
echo "<br />";
}
else
{
echo "<h4>Result 2</h4>";
echo "<br />";
}
I've tried every possible variation I can think of to this code but all I can get is it to echo either Array or Resource #9. Any insight into this would be greatly appreciated.
You do not want to echo the content of $row, which contains all data returned for the current line you've fetched from the database when calling mysql_fetch_array().
Instead, you want to access the content of $row's pool item :
echo $row['pool'];
You should probably take a closer look at the manual page for mysql_fetch_array(), and the examples it contains.
Note that you'll probably also want to modify the condition in the following line :
if ( $row % 2 )
You probably don't want the test to be done on $row, but on an item it contains.
$query = "SELECT pool FROM winners";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
if ( $row['pool'] % 2 )
{
echo "<h4>Result 1</h4>";
echo "$row['pool']";
echo "<br />";
}
else
{
echo "<h4>Result 2</h4>";
echo "<br />";
}
}
Hope this helps.
I've been trying for hours to figure out how to put a link into the following text output via PHP echo(). I basically want to make the title field I'm pulling from my events table (as seen in #4 in the code below) to come back into the browser as a link instead of just text...
the original code that brings back the event title:
<?php
// 3. Perform database Query to bring list of events
$result = mysql_query("SELECT * FROM events", $connection);
if (!$result) {
die("Database query failed: " . mysql_error());
}
// 4. Use returned Data
while ($row = mysql_fetch_array($result)) {
echo $row ["eventtitle"]."<br/>".$row["eventdesc"]."<br/>";
}
?>
How would I go about getting that $row["eventtitle"] to appear in the browser as a link? Let's say if the link was just "eventprofile.php". This is probably an easy fix, but I've been getting a million errors with trying different things with <a href>s.
<?php
$result = mysql_query("SELECT * FROM events", $connection);
if (!$result) {
die("Database query failed: " . mysql_error());
}
while ($row = mysql_fetch_array($result)) {
echo "".$row["eventtitle"]."<br/>".$row["eventdesc"]."<br/>";
}
?>
add an anchor tag for it!!
echo "" . $row['eventtitle'] . '' . "<br />" .$row["eventdesc"]."<br/>";
And thats it.