I've just started learning PHP so this is quite a struggle for me, any help is appreciated!
So, I've managed to select my database, table and get data from it. But I need to select more data from the older columns.
Here is some of the code:
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//execute the SQL query and return records
$result = mysqli_query($conn, "SELECT username FROM interview");
while($rowval = mysqli_fetch_array($result))
{
$username= $rowval['username'];
$username2= $rowval['username'];
$username3= $rowval['username'];
$username4= $rowval['username'];
}
?>
And I am displaying the data in a button, I want $username to display the first column and $username2 to display the second column etc...
I fetch the data using this code:
<?php echo $username; ?>
<?php echo $username2; ?>
<?php echo $username3; ?>
<?php echo $username4; ?>
Thanks!
I would suggest you re-factoring your "while" loop the following way for better scalability:
$usernames=array();
while($rowval = mysqli_fetch_array($result))
{
$usernames[] = $rowval['username'];
}
Then, you'll be able to access usernames like:
echo 'The first user name is: '.$usernames[0];
echo 'The second user name is: '.$usernames[1];
echo 'The third user name is: '.$usernames[2];
My php skills are a bit rusty, so take this with a grain of salt:
At first it is important to get the language right. A database table consists of rows and columns, the columns are the ones you select with the the part after the SELECT statement, if you write SELECT username what you select is the username column.
SELECT username FROM interview;
So if you want to select more columns from your table you have to put them in your SELECT statement. Let's say you want to select the username and the status of the interview, you would need to include the status in your SELECT statement like this:
SELECT username, status from interview;
Then you can access the interview status just like you did it with the username.
$result = mysqli_query($conn, "SELECT username, status from interview;");
while($rowval = mysqli_fetch_array($result))
{
$username= $rowval['username'];
$status = $rowval['status'];
}
Remember that what you get as the $rowVal is just a single row of your table. So if you want to collect all usernames and statuses from your table you have to use a datastructure to collect them.
$queryResult = mysqli_query($conn, "SELECT username, status from interview;");
$result = array();
while($rowval = mysqli_fetch_array($queryResult))
{
$username= $rowval['username'];
$status = $rowval['status'];
// With this action we build an array, that has each row's result as value.
$result[] = array('username' => $username, 'status' => $status);
}
To access the results you can then query the $result array like this:
// The interview status of the first entry in your table
$result[0]['status'];
Related
I'm trying to loop through each row of a table in a database, then once I'm on a particular row get the value of a certain column. Is this possible? I've done a couple Google searches but nothing really concrete. I try using the mysqli_fetch_array() function but when I do I get the results of a column. I want to target each row. The code I have so far gets me the "nid" column. That's not what I want. I want to iterate through each row.
<?php
$serverName = "localhost";
$username = "user1";
$password = "sp#99#1";
$databaseName = "developer_site";
// Connection
$connection = new mysqli($serverName, $username, $password, $databaseName);
// Check Connection
if ($connection->connect_error) {
die("Connection failed:" . $connection->connect_error);
} // line ends if statement
$queryNodeRevision = "SELECT nid FROM node_revision";
// line above creates variable $queryNodeRevision > selects column "nid" from table "node_revision"
$results = mysqli_query($connection, $queryNodeRevision) or die("Bad Query: $results");
while ($row = mysqli_fetch_array($results)) {
echo "NID: ";
echo $row['nid'];
echo "<br/>";
}
?>
You can select rows by a certain condition with an SQL query alone and also select all columns.
SELECT * FROM node_revision where condition;
condition could be anything. For example another_row = 'something'.
But if, for some reason, you need to process the nid inside your php script to know if that row is the "particular" one you're searching, then you just select all the columns, or the ones you need.
$queryNodeRevision = "SELECT nid, col1, col2 FROM node_revision";
$results = mysqli_query($connection, $queryNodeRevision) or die("Bad Query: $results");
while ($row = mysqli_fetch_array($results)) {
if (condiiton) {
echo "Particular: ".$row['nid']
." ".$row['col1']
." ".$row['col2'];
}
}
condition could be something like $row['nid'] == 123 for example.
Hope it helps.
The purpose behind this, is for me to be able to extract data from a table thats been formed via INNER JOIN of two other tables.
I've mapped a tariff name to a username successfully. But what i want to do is to be able to return data from this new table that was created via INNER JOIN in a text field on android studio.
My main concern at the moment is figuring out the right query to do be able to return the data. I've tried researching this but have had no luck/
I have 2 databases. A useraccount database and a tariff database.
useraccount database consists of the following columns:
ID
Name
Surname
EmailAddress
PostCode
City
PhoneNumber
Username
Password
ConfirmPassword
tariffs
And my Tariff database consists of the following column:
ID
Name
I have joined the two tables using INNER JOIN, and have linked the username column with the tariff name column, essentially, i ended up with a table like this:
Username|Tariff
Here is the code for that:
$query = "SELECT useraccount.Username, tariff.Name as tariffs
FROM useraccount
INNER JOIN tariff ON useraccount.tariffs = tariff.id";
$result = mysqli_query($conn,$query);
if($result->num_rows){
while($row = $result ->fetch_object()){
echo "{$row->Username} ({$row->tariffs}) <br>";
}
}else{
echo "No results";
}
$query2 = "SELECT";
$result2 = mysqli_query($conn,$query2);
Question:
How do I access the columns of the result set?
This image shows the result of the execution of the PHP file
Joining two tables together does not create a third table, but creates a result set from the combined records of the two tables. In your code example, you already have access to all the data contained in the useraccounts and tariff tables. To gain access to this data, simply modify your select statement so that it references the desired columns. You could also just use the '*' wildcard to include all columns in your result set.
// Using a wildcard to get all useraccount data.
$query = "SELECT useraccount.*, tariff.Name as tariffs
FROM useraccount
INNER JOIN tariff ON useraccount.tariffs = tariff.id";
$result = mysqli_query($conn,$query);
if($result->num_rows){
while($row = $result ->fetch_object()){
// Reference any user data you want.
echo "{$row->Username} {$row->EmailAddress} {$row->PostCode} ({$row->tariffs}) <br>";
}
}
You need to join the user account id on the tariff id:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT useraccount.Username, tariff.Name FROM useraccount INNER JOIN tariff ON useraccount.id = tariff.id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "Username: " . $row["username"]. " - Tarrif: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
Hello I've a table named as "register" in which i've some records Lets says (10)
I want to first count that records and then save it into another table named as "not" i.e. Notification(Handler Name)
Here's the code which i'm using but unfortunately its not working..
Here's my config.php
<?php
$con = new mysqli('localhost','root','','admin');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
and here's abc.php
<?php
include('config.php');
$sql2 = "INSERT INTO not VALUES((SELECT count(*) as count FROM register))";
$result2 = mysqli_query($con, $sql2);
if($result2->num_rows>0)
{
while($rw1=$result2->fetch_array())
{
$value1 = $rw1['count'];
echo $value1;
}
}
?>
not is reserved word. So you should use like this:
$sql2 = "INSERT INTO `not` VALUES((SELECT count(*) as count FROM register))";
Basically i'm working on a project similar to Facebook Notification System
I've a Registration Form through which users are registered and all entries will be saved in a database named as "admin" with table name as "register"
Clear or not ?
Suppose I've 10 Users and I want to first show No. 10 as Notification Number at top bar as a popup tooltip
Just follow this example which i'm using
[http://demos.9lessons.info/notifications_css/index.php][1]
After that I want to Perform this thing that when someone opens the notification bubble, that 10 Number Goes out and in backend, i'm thinking that to store that ROW COUNT into another table and after Jquery click function, that table value goes to ZERO and when any new user is registered, then it increments the counter with match the previous value..
Sounds or not ??
change your table name as suggested by #phpPhil
plus try this query
$sql2="INSERT INTO not SELECT count(*) as count FROM register";
UPDATED
made your connection in this file.
$con = new mysqli('localhost','root','','admin');
$sql = "SELECT count(*) as count FROM register";
this query will return only one or zero rows so dont use while
$result = $con->quer($sql) or die($con->error);
if($result->num_rows>0)
{
$rw=$result->fetch_array(MYSQLI_ASSOC);
$value = $rw['count'];
echo $value; here to check what you get here
//preiously you had check if value is not empty. which is wrong because it will never empty it will either 0 or any other value
if($value!=0)
{
$jh ="update noti set noti='$value'";
$res=$con->query($jh) or die($con->error);
}
else
{
$ab ="insert into noti(noti) values('$value')";
$res1=$con->query($ab) or die($con->error);
}
}
So I am trying something totally new (for me). I have a PHP file where I try to retrieve the data of 2 tables and replace values if they match. Since I'm not really sure what I'm doing I'm kinda stuck:) Here is what i want:
I have 2 tables in my mysql database.
The table 'advertisement' has the column 'logo_fid'.
The table 'files' has the columns 'fid' and 'filepath'.
Now I would like to echo the values of the 'logo_fid' column in the 'advertisement' table.
Before that, however, I would like to see if in the table 'files' a corresponding value is stored in the 'fid' volumn and if so I would like to echo the value of 'filepath' instead of the value of 'logo_fid'.
So basically what I want is to replace the returned value of the logo_fid column, if this value matches with the value in the 'fid' column, with the corresponding 'filepath' value.
Hope I made myself clear. Anyway I have this code atm. Hope that anybody can help me out with this one. Thanks a lot!
<?php
//connection info xxxx
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//advertisement SELECT
$sql = "SELECT logo_fid FROM advertisement ORDER BY nid ASC";
$result = $conn->query($sql);
//advertisement SELECT
$sql2 = "SELECT fid, filepath FROM files";
$result2 = $conn->query($sql2);
if ($result->num_rows > 0 && $result2->num_rows > 0) {
// output data of each row
while(($row = $result->fetch_assoc()) && ($row2 = $result2->fetch_assoc())){
//So after i received all the info i'd like to check if the value of logo_fid matches with fid and if so replace the value with the value of filepath
if ($row["logo_fid"] == $row2["fid"]) :
echo $row2["filepath"];
else :
echo $row["logo_fid"];
endif;
echo '<br>';
}
} else {
echo "0 results";
}
$conn->close();
?>
Seems like this could be done as one query.
SELECT A.logo_Fid, F.Fid, F.filePath, coalesce(F.FilePath, Logo_Fid) as ValueYouWant
FROM advertisement A
LEFT JOIN files F
on A.logo_Fid = F.FID
Then you can echo ValueYouWant without the inline logic.
The join relates the two tables on the Fid and logo_fid.
if a match is found, Valueyouwant will contain the f.filepath, if no match is found logo_fid will be in valueyouwant.
Since this is using a LEFT join, all values from advertisement will be returned, and only related records from files will be returned.
so to display...
I don't do much PHP, but an online search that was accpted as an answer indicates it would be something like this...
$sql=" SELECT A.logo_Fid, F.Fid, F.filePath, coalesce(F.FilePath, Logo_Fid) as ValueYouWant
FROM advertisement A
LEFT JOIN files F
on A.logo_Fid = F.FID ORDER BY NID asc"
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
echo $row['ValueYouWant'];
echo '<br>';
}
How do I fetch only one value from a database using PHP?
I tried searching almost everywhere but don't seem to find solution for these
e.g., for what I am trying to do is
"SELECT name FROM TABLE
WHERE UNIQUE_ID=Some unique ID"
how about following php code:
$strSQL = "SELECT name FROM TABLE WHERE UNIQUE_ID=Some unique ID";
$result = mysql_query($strSQL) or die('SQL Error :: '.mysql_error());
$row = mysql_fetch_assoc($result);
echo $row['name'];
I hope it give ur desired name.
Steps:
1.) Prepare SQL Statement.
2.) Query db and store the resultset in a variable
3.) fetch the first row of resultset in next variable
4.) print the desire column
Here's the basic idea from start to finish:
<?php
$db = mysql_connect("mysql.mysite.com", "username", "password");
mysql_select_db("database", $db);
$result = mysql_query("SELECT name FROM TABLE WHERE UNIQUE_ID=Some unique ID");
$data = mysql_fetch_row($result);
echo $data["name"];
?>
You can fetch one value from the table using this query :
"SELECT name FROM TABLE WHERE UNIQUE_ID=Some unique ID limit 1"
Notice the use of limit 1 in the query. I hope it helps!!
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT name FROM TABLE WHERE UNIQUE_ID=Some unique ID";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["name"]."<br>";
}
} else {
echo "0 results";
}
$conn->close();