$aRow = array();
$query = "SELECT id, name FROM myTable";
while ($row = mysqli_fetch_assoc($db, $query)) {
$aRow[] = $row;
}
Now that I have several records in $aRow[], I'd like to iterate the $aRow[id] like this:
foreach ($aRow as $thisRow) {
$anID = $thisRow[id];
$query = "SELECT amount FROM mySubTable WHERE myTableID = {$anID}";
.
.
.
}
That doesn't seem to work - $anID doesn't have the expected value. How do I address the associative PHP array?
ETA: To more finely filter my question, after the WHILE completes, I have an array of DB records in $aRow[] that correspond to the database. Maybe I have: $aRow[1, 'Sally'], $aRow[2, 'Dick'], and $aRow[3, 'Jane'].
How to I assign a new variable to 'Dick'? $myVar = $aRow[?] such that $myVar will equal 'Dick'?
$link = new mysqli('localhost', 'myuser', 'mypass', 'dbname');
$query1 = "SELECT id, name FROM myTable";
$result1 = $link->query($query);
while ($row = result1->fetch_array(MYSQL_ASSOC))
{
$query2 = "SELECT amount FROM mySubTable WHERE myTableID = $row[id]";
$result2 = $link->query($query);
.
.
.
}
May be the above code is what you are looking for
Related
I'm trying to make a Check-in/out system.
So far I have a dropdown that get the list of active events.
<select name="events">
<?php
$conn = new mysqli('localhost:3306', 'user', 'pw', 'database') or die ('Cannot connect to db');
$eveny = $conn->query("select event_title from events_event where inactive=0");
while ($row=mysqli_fetch_array($eveny)) {
unset($event);
$event = $row['event_title'];
echo '<option value="'.$event.'">'.$event.'</option>';
}
?>
</select>
And a textbox that searches users based on first name, but it auto displays results (like a Google search) and then fills out the info with both First Name and Last name. Source.
The only change in the php is the echo to show both first and last names as follows:
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
echo "<p>" . $row["per_FirstName"] . " " . $row["per_LastName"] . "</p>";
}
NOW FOR THE PROBLEM
I have made the frontend into a form, and a submit button using method="post".
But something in my php is not functioning/lacking.
<?php
$db = new mysqli('localhost:3306', 'user', 'pw', 'database') or die ('Cannot connect to db');
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST") {
$myname = mysqli_real_escape_string($db,$_POST['fullname']);
$eventy = mysqli_real_escape_string($db,$_POST['events']);
//$checktime = mysqli_real_escape_string($db,date("Y-m-d H:i:s"));
$evid = "SELECT event_id from events_event where event_title = '$eventy'";
$revvy = mysqli_query($db,$evid);
$nameParts = explode(' ', $myname);
$firstName = trim($nameParts[0]);
$lastName = trim($nameParts[1]);
$sql = "SELECT per_ID FROM person_per WHERE per_FirstName = '$firstName' AND per_LastName = '$lastName'";
$result = mysqli_query($db,$sql);
//$row = mysqli_fetch_row($result);
//$result = $result->fetch_all();
while($row = mysqli_fetch_assoc($result)){
$perID = $row['per_ID'];
}
while($row2 = mysqli_fetch_assoc($revvy)){
$evvy = $row['event_ID'];
}
$count = mysqli_num_rows($result);
// table row must be 1 row if it succeeded
if($count == 1) {
//session_register("myname");
//$_SESSION['login_user'] = $myname;
$checkin = "insert into event_attend (attend_id, event_id, person_id, checkin_date) values (DEFAULT, '$evvy', '$perID', now())" or die(mysqli_error());;
mysqli_query($db,$checkin);
header("location: checkedin.php");
}else {
$error = "An error occurred.";
}
}
?>
The $myname, is the result of both first name and last name, I need just First Name based on the filled out text field which uses both first and last names.
I also can't get the Event_ID from the dropdown.
If user's first and last name are separated by space:
$nameParts = explode(' ', $myname);
$firstName = trim($nameParts[0]);
I have two rows contaning data of same id.
It has different adresses in different rows for the same id.
I want to fetch both the adress in different variable in php.
How can i do this? Please help!
Below is the code:
foreach($row_address as $address)
{
echo "<br> Address :" .$address;
$info=Array();
$data=explode(' ', $address );
$info[1]=$data[0];
$info[2]=$data[1];
$info[3]=$data[2];
echo "City :".$info[1];
echo "Country :".$info[2];
echo "Pin Code :".$info[3];
}
function hoteladdresstable($id)
{
global $conn;
/*$sql2 = "select AddressLine from hoteladdress where Hotel_Id= " .$id;
$result2 = mysql_query($sql2,$conn);
$row2 = mysql_fetch_assoc($result2,MYSQL_NUM);
return $row2;*/
$query = "select AddressLine from hoteladdress where Hotel_Id = " .$id;
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result))
{
$d[] = $row['AddressLine'];
}
return $d;
}
It gives me both the address of the same id in one variable only.
I want them in two different variables.
You are already getting an array of addresses in $d.
What you can do is:
$d = array();
while ($row = mysql_fetch_assoc($result)) {
$d[$row['Address_ID']] = $row['AddressLine'];
}
extract($d, EXTR_PREFIX_ALL, 'ad');
If you have address ids 2 and 4, you will get two variables
$ad_2 and $ad_4
You should use parameterized queries. Use PHP's PDO:
$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$STH = $DBH->prepare('select AddressLine from hoteladdress where Hotel_Id = :id');
$STH->bindParam(':name', $id);
$STH->execute();
$d = array();
while($row = $STH->fetch()) {
$d[] = $row['AddressLine'];
}
http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059
Don't want your queries getting injected with attacks.
I suggest you to use mysqli instead.
$data = array();
while($row = mysqli_fetch_assoc($result)){
$data[] = $row;
}
return $data;
and then
foreach($data as $oneRow){
echo $oneRow['AddressLine']; //and all other stuff that you want.
}
you can verify it:
print_r($data);
I've done this:
$result = mysql_query("SELECT image, id FROM store WHERE username = '$username_show'");
$num_rows = mysql_num_rows($result);
$ids = mysql_fetch_assoc($result);
$ids = $ids['id'];
for ($i = 0; $i < $num_rows; $i++) {
echo "<img src='get.php?id=$ids[$i]' height='300'><p/>";
}
I want to show all of my photos that has that username. But the $ids array only gets one index, and that's the last ID. What am I doing wrong?
Like #Matthew said thet are deprecated use :
// mysqli
$mysqli = new mysqli("example.com", "user", "password", "database");
$result = $mysqli->query("SELECT image, id FROM store WHERE username = '$username_show'");
$row = $result->fetch_assoc();
echo htmlentities($row['row']);
// PDO
$pdo = new PDO('mysql:host=example.com;dbname=database', 'user', 'password');
$statement = $pdo->query("SELECT image, id FROM store WHERE username = '$username_show'");
$row = $statement->fetch(PDO::FETCH_ASSOC);
echo htmlentities($row['row']);
To answer your comment :
- use the array function
$result_array = array();
while($row = mysql_fetch_assoc($result))
{
$result_array[] = $row;
}
$result = $mysqli->query("SELECT id FROM store WHERE username = '$username_show'");
$result_array = array();
while($row = mysqli_fetch_assoc($result))
{
$result_array[] = $row;
}
<?php
$tid = $_GET['tid'];
$id = $_SESSION['userid'];
$sql1 = "SELECT * FROM topics WHERE id='$tid' LIMIT 1";
$res1 = mysqli_query($connect, $sql1) or die(mysqli_error($connect));
while ($row = mysqli_fetch_array($res1, MYSQLI_ASSOC)) {
$title = $row['topic_title'];
$creator = $row['topic_creator'];
}
$sql = "SELECT * FROM users WHERE id='$creator' LIMIT 1";
$user_query = mysqli_query($connect, $sql) or die(mysqli_error($connect));
while ($row = mysqli_fetch_array($user_query, MYSQLI_ASSOC)) {
$name = $row["first"].$row["last"];
}
echo $name;
?>
I'm a little new to PHP, but I've done things exactly like this, but this time I'm getting an error. Everything here works except for $name. I checked my SQL tables and made sure users exist and that there's first and a last area. I don't see what else could be wrong.
Notice: Undefined variable: name in * on line **
Thank you.
Try this code on for size:
<?php
$tid = $_GET['tid'];
$id = $_SESSION['userid'];
$tid = mysqli_escape_string($connect, $tid);
$sql1 = "SELECT * FROM topics WHERE id='{$tid}' LIMIT 1";
$res1 = mysqli_query($connect, $sql1) or die(mysqli_error($connect));
// Check for rows first.
if($res1 and mysqli_num_rows($res1)){
// Use if as while is pointless on LIMIT 1
if($row = mysqli_fetch_array($res1, MYSQLI_ASSOC)) {
$title = $row['topic_title'];
$creator = $row['topic_creator'];
$creator = mysqli_escape_string($connect, $creator);
$sql = "SELECT * FROM users WHERE id='{$creator}' LIMIT 1";
$user_query = mysqli_query($connect, $sql) or die(mysqli_error($connect));
// Check for rows first.
if($user_query and mysqli_num_rows($user_query)){
// Use if as while is pointless on LIMIT 1
if ($row = mysqli_fetch_array($user_query, MYSQLI_ASSOC)) {
$name = $row["first"].$row["last"]; // NO HIT!
}
echo $name;
}else{
echo 'no rows found (query 2).';
}
}
}else{
echo 'no rows found (query 1).';
}
?>
Variable $name is undefined because the $name = ...; line is not reached. So make sure you $sql query actually returns results. It has to in order to define $name.
Hi I would like to display the number of item in the database. The following is the php code:
$jobid = $_SESSION['SESS_MEMBER_JOB'];
$data = "SELECT * FROM attributes WHERE jobid = $jobid";
$attribid = mysql_query($data) or die(mysql_error);
$count = "SELECT count(*) FROM attributes WHERE jobid = $jobid";
$database_count = mysql_query($count);
//Declare the Array
$DuetiesDesc = array();
print_r ($database_count);
But instead of getting the desired result, I get :
Resource id #14
Please Assist
Should get it out of the way that you shouldn't be using mysql_* see Why shouldn't I use mysql_* functions in PHP?
See the code below... explanations are in comments
$jobid = $_SESSION['SESS_MEMBER_JOB'];
// escape variables using mysql_real_escape_string
$data = "SELECT * FROM attributes WHERE jobid =".mysql_real_escape_string($jobid);
$attrRes = mysql_query($data) or die(mysql_error());
// I'm assuming you want all of the attributes return in this query in an array
$attributes = array();
while($row = mysql_fetch_assoc($attrRes)){
$attributes[] = $row;
}
// Now if you want the count we have all of the records in the attributes array;
$numAttributes = count($attributes);
// here is an example of how you can iterate through it..
print "<p>Found ".$numAttributes." attributes</p>";
print "<table>";
foreach($attributes as $row){
print "<tr>";
foreach ($row as $cell){
print "<td>".$cell."</td>";
}
print "</tr>";
}
print "</table>";
Try this
<?php
$jobid = $_SESSION['SESS_MEMBER_JOB'];
$data = "SELECT * FROM attributes WHERE jobid =$jobid";
$attribid = mysql_query($data) or die(mysql_error);
$count=mysql_num_rows($attribid);
echo $count;
?>
try this
$jobid = $_SESSION['SESS_MEMBER_JOB'];
$data = "SELECT *FROM attributes WHERE jobid =$jobid";
$attribid = mysql_query($data) or die(mysql_error);
$count = "SELECT count(*) FROM attributes WHERE jobid = $jobid";
$database_count = mysql_query($count);
//Declare the Array
$DuetiesDesc = array();
$database_count=mysql_fetch_assoc($database_count);
echo $database_count['count(*)'];