so I have a list of people with their city name and contact numbers in mysql database which is displayed on my website. I want to know which person was contacted by a visitor.
Here is a snippet of my code:
<?php
$city = $_POST['city'];
$sql = "SELECT * FROM users WHERE city = '$city'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$id = $row['id'];
?>
<tr>
<td class="pl-4"><?php echo "<h3>" .$row['fname']. " " .$row['lname']. "</h3>"; ?>
<BUTTON onClick="contactclick();" class="track btn btn-outline-info p-2"><span class="icon-phone"></span> Contact</BUTTON>
</td>
<script>
function contactclick() {
<?php
$sql7 = "SELECT * FROM users WHERE id = '$id' LIMIT 1";
$result7 = mysqli_query($conn, $sql7);
$row7 = mysqli_fetch_assoc($result7);
$firstname = $row7['fname'];
$lastname = $row7['lname'];
$city7 = $row7['city'];
$txt = 'Call received by:'.$firstname.' '.$lastname.' of '.$city7.'';
$file = fopen('drivers-contacted.txt','a');
fwrite($file,$txt);
?>
}
</script>
</tr>
As you can see from the code I have tried making a text file and adding info into that file everytime 'contact' button is clicked. But it adds the name of all people in the list instead of 1 who was actually contacted. How can I solve this? Also, is there a better way to get the information I want, like which user was contacted from my database list?
PS : I'm new to coding
In general: you are trying to communicate in the direction of client-side to server-side when you want to do a server-side action on a button click. Embedding PHP code inside the client script is not the correct way to do this. Please look up AJAX. A library called jQuery is fairly easy to use and has a simple interface for AJAX.
In addition: unless there is some code missing from this snippet, what this appears to do is create n contactclick() functions, each with its own ID. You need to take the function out of the loop, and have it accept id as a parameter. Then you can do an AJAX call from this function and your back-end (PHP) code will write to a file.
Related
Ok so eventually I will have let's say 100 products in mysql database. The product page pulls all info from database (such as partnumber, material, color, etc...) and inputs it into the areas of the page that I designate it, all this using php. The previous page will show all 100 products and when user click's on one product it'll go to that product page. Just like all websites right...
I don't believe I need to make 100 individual html pages for each product right? Can I make just 1 main html page that is the templet for the 100 different products? Basically when user clicks the image tag of the product(1st example of code) it'll open the main html templet but somehow call to the database on open and load that specific info? Then other products will have the same process but for they're specific data from database. The 1st sample code is one product on the page that'll display all 100 products with the href containing the image that'll get clicked to show user actual product page retrieved dynamically without page reload, into a predestined section. I'm sure there is a name for what I'm looking to do but all the research I've done I haven't found what I'm looking for. Is there a better way then what I'm explaining? Also I hope this makes sense, Thank you for any input.
<td><img class="td-Image" src="image.jpg">
</td>
<td class="td-manufacturer">
<h6>MANUFACTURER</h6>
<p>Lowes</p>
</td>
<td class="td-addComponent">
<p>$104.99</p>
<button class="add-button">ADD</button>
</td>
<td class="td-material">
<h6>MATERIAL</h6>
<p>Aluminum 7075-t6 Forged</p>
</td>
<td class="td-platform">
<h6>PLATFORM</h6>
<p>Large</p>
</td>
<td class="td-america">
<h6>AMERICAN MADE</h6>
<p>YES</p>
</td>
Actual product page where php gets info from database example
<?php
$sql = "SELECT * FROM Parts;";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
?>
<div class="description">
<h3>Descrption</h3>
<p>
<?php
echo $row['Description'];
?>
</p>
</div>
<?php
}
}
?>
Editor Note: I edited the question to reflect what he want based on thread on my answer below.
In this scenario you would need to pass in a unique identifier i.e product-id and create a query to fetch from the database product info by product-id
$product-id= $_GET['id'];
$strSQL = "SELECT * FROM AR15Parts WHERE id='$product-id'";
$rs = mysql_query($strSQL);
if (!$rs) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_assoc($rs);
//display your data
if($row){
echo $row['field'];
}
Add an unique Id to your products in your mysql database, using the Auto Increment option (A_I checkbox in phpmyadmin). Then you can pass that id into a link to the product page ```href=“individualProduct.php?id=” while rendering all the products on the all products page.
Then in individualProduct.php you can get that id and retrieve the data
$sql = SELECT * FROM Parts WHERE id =?”;
$stmt = mysqli_prepare($sql);
$stmt->bind_param($_GET[“id”]);
$stmt->execute();
$result = $stmt->get_result();
// Do stuff with $result as it is the individual product corresponding to that id
Optimally, you'll need 2 files:
index/list of products
detail information of the selected product
index files (maybe call it index.php)
Here, you need to select products and make it a list:
$stmt = $pdo->query("SELECT * FROM Parts");
while ($row = $stmt->fetch()) {
echo '' . $row['name']."<br />\n";
}
Since you want the detail to be shown to the index/list page, let's add a container area:
<div id="container-detail">
</div>
Add a little javascript code to handle AJAX request:
<script type="text/javascript">
function loadDetail(itemId){
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://website.address/path/to/detail.php?id=" + itemId, true);
xhr.onreadystatechange = function ()
{
if (xhr.readyState==4 && xhr.status==200)
{
document.getElementById("container-detail").innerHTML=xhr.responseText;
}
}
xhr.send();
}
</script>
detail page (let's call it detail.php)
In this screen, we fetch details for only one part, specified by HTTP GET id parameter. The one that's being supplied from index.php (the ?id= part).
$stmt = $pdo->query("SELECT * FROM Parts WHERE id = '" . $_GET['id'] . "'");
$part = $stmt->fetch();
echo "Name: " . $part['name'] . "<br />\n";
echo "Manufacturer: " . $part['manufacturer'] . "<br />\n";
echo "Price: " . $part['price'] . "<br />\n";
That's it, you should get it working with a few adjustments based on the table and template you have.
A little note is that I used PDO mechanism to do the query. This is because mysql_* function has been deprecated for so long that it is now removed from PHP 7.0. Also, the current PHP version has been PHP 8. So, be prepared, a lot of web hosting might gonna remove older PHP versions, moving forward.
I'm trying to display data from database and it is important to me that this output is placed on different sides of website. I used php to connect to database, and ajax jquery to refresh data because every 20second values change.
I tried to
echo <div styles='position: absolute; top: 0px' class='text'>{$row['id']}</div>
in a foreach loop but when I do this all 6 of my id's are stacked on top each other.
Making <div> outside loop was unsuccessful too. I guess my problem is in reading data from database because I read all at once but I don't know any other way to do this except wrtiting 6 connection files to gather only the one value that I want to display and then styling it, but I feel like there is smarter way of doing this.
This is my code. Just want to say this is my first contact with php.
<?php
$hostname = "someinfo";
$username = "someinfo";
$password = "someinfo";
$db = "someinfo";
$dbconnect = mysqli_connect($hostname,$username, $password,$db) or die("cant");
if ($dbconnect->connect_error) {
die("Database connection failed: " . $dbconnect->connect_error);
}
$sensor_names = array();
$query2 = mysqli_query($dbconnect,"show tables");
while($row2 = mysqli_fetch_array($query2)){
if($row2[0] == 'sensors' or $row2[0] == 'measurments'){
break;
}
else{
array_push($sensor_names,$row2[0]);
}
}
$query = mysqli_query($dbconnect, "select s.id, s.sensor_name, max(dev.id), dev.temprature, dev.date from sensors s, `{$sensor_names[0]}` dev where s.id=dev.sensor_id gro
up by s.id, s.sensor_name order by s.id asc");
while($row = mysqli_fetch_array($query)){ //i konw this is ugly but this is working placeholder
foreach($sensor_names as $sn){
$query = mysqli_query($dbconnect, "select s.id, s.sensor_name, dev.temprature, dev.date from sensors s, `{$sn}` dev where s.id=dev.sensor_id order by dev.id desc limit 1");
$row = mysqli_fetch_array($query);
echo "
{$row['id']}
{$row['sensor_name']}
{$row['temprature']}
{$row['date']}
<br>";
}
}
?>
This is off-the-cuff from a guy who hasn't touched PHP in a long while, so watch for major bugs. But the basic idea is like this: build the code in a variable, and when done, echo out the entire variable. Makes it easier to add the structure/formatting you want. Note that you can also stick in a style tag along with that code and blurp out the style along with the "table" (Personally, I wouldn't use a table for styling, this is just for demo).
Note: I didn't style the output so that it puts the data on either side of the page - I left that for you to do. It's basic HTML - divs, styles, maybe css grid or flexbox. The point is to create your CSS/HTML/PHP mashup in a string variable and output the entire thing when done.
$out = '<style>.cell_id{font-weight:bold;}</style>';
$out .= '<table><tr><th>Label 1</th><th>Label 2</th><th>Etc</th></tr>'; //<=== ADDED!
while($row = mysqli_fetch_array($query)){
foreach($sensor_names as $sn){
$query = mysqli_query($dbconnect, etc. etc. etc.);
$row = mysqli_fetch_array($query);
$out .= "
<tr>
<td class='cell_id'>{$row['id']}</td>
<td>{$row['sensor_name']}</td>
<td>{$row['temprature']}</td>
<td>{$row['date']}</td>
</tr>";
}
}
echo $out;
Ok I think I got it. Cssyphus's answer got me thinking and I wrote something like that array_push($data, $row) and $data is two dimentional array that hold all data I need and now I can style it easily.
Being a huge PHP newbie I find myself stuck here.
I have an HTML table for a videogame store filled with elements taken from my database.
The point is, I want to be able to add a link to the game title. Moreover I want the link to direct to some "gamePage.php", a php page used for every videogame but of course showing different infos for each game (title, console etc).
The fact is that not only I can't add the hyperlink, but I have no clue on how to carry the videogame infos when I click on a link (even managing to add the link, all I would manage to do would be redirecting the user to a blank gamePage.php with no title).
This is the code I use to fill the table (the restore function fills my table):
<html>
<body>
<div>
<table width = "550px" height = "300px" border="2" >
<tr bgcolor="#5f9ea0">
<td>Title</td>
<td>Console</td>
<td>Genre</td>
<td>Price</td>
</tr>
<?php
$conn = #pg_connect('dbname=project user=memyself password=project');
function search(){
<!-- Work in progress -->
}
function restore(){
$query = "SELECT v.Title , c.Consolename , g.Genrename , v.Price
FROM vg_shop.videogame v, vg_shop.console c, vg_shop.genre g
WHERE v.Console=c.IDConsole AND v.Genre=g.IDGenre";
$result = pg_query($query);
if (!$result) {
echo "Problem with query " . $query . "<br/>";
echo pg_last_error();
exit();
}
while($myrow = pg_fetch_assoc($result)) {
printf ("<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>",
$myrow['title'], $myrow['consolename'], $myrow['genrename'], $myrow['price']);
}
}
<!-- some code -->
</body>
</html>
At first i tried to do this
while($myrow = pg_fetch_assoc($result)) {
printf ("<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>",
$myrow['title'], $myrow['consolename'], $myrow['genrename'], $myrow['price']);
But all I get is a white page, there's some syntax error I don't get.
And, even if it worked, I still can't carry at least the videogame PID through the gamePage link
so, you're managing to go to gamepage.php somehow.
So you need to add some sort of identifier to your link you that you could do some query on the gamepage.php by using that identifier to get info for that particular game.
while($myrow = pg_fetch_assoc($result)) {
printf ("<tr><td><a href='gamePage.php?id=%s'>%s</a></td><td>%s</td><td>%s</td><td>%s</td></tr>", $myrow['id'], $myrow['title'], $myrow['consolename'], $myrow['genrename'], $myrow['price']);
Note: I assume that you're picking $myrow['id'] from database as well.
now on your gamepage.php do following.
$id = $_GET['id'];
$sql = "SELECT * FROM vg_shop.videogame WHERE `id` = $id";
$result = pg_query($sql);
if($result){
$result = pg_fetch_assoc($result):
//...
// echo "Name: ".$result['Title'];
// other fields
}
$result will have all info about that particular game that was clicked, you can display all as you want.
Cheers :)
I'm trying out my hand at php at the moment - I'm very new to it!
I was wondering how you would go about selecting all items from a mySQL table (Using a SELECT * FROM .... query) to put all data into an array but then not displaying the data in a table form. Instead, using the extracted data in different areas of a web page.
For example:
I would like the name, DOB and favorite fruit to appear in one area where there is already say 'SAINSBURYS' section hardcoded into the page. Then further down the next row that is applicable to 'ASDA' to appear below that.
I searched both here and google and cant seem to find an answer to my strange questions! Would this involve running the query multiple times filtering out the sainsburies data and the asda data where ever I wanted to place the relevant
echo $row['name']." ";
echo $row['DOB']." "; etc etc
next to where it should go?
I have got php to include data into an array (I think?!)
$query = "SELECT * FROM people";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result) or die(mysql_error());
while($row = mysql_fetch_assoc($result))
{
echo $row['name']." ";
echo $row['DOB']." ";
echo $row['Fruit']." ";
}
?>
Just place this (or whatever your trying to display):
echo $row['name']." ";
Anywhere you want the info to appear. You can place it within HTML if you want, just open new php tags.
<h1>This is a the name <?php echo $row['name']." ";?></h1>
If you want to access your data later outside the while-loop, you have to store it elsewhere.
You could for example create a class + array and store the data in there.
class User {
public $name, $DOB, $Fruit;
}
$users = new array();
$query = "SELECT * FROM people";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)) {
$user = new User;
$user->name = $row["name"];
$user->DOB = $row["DOB"];
$user->Fruit = $row["Fruit"];
$users[$row["name"]] = $user;
}
Now you can access the user-data this way:
$users["USERNAME"]->name
$users["USERNAME"]->DOB
$users["USERNAME"]->Fruit
I am having some difficulty using PHP with jQTouch. I am fairly
confident with JavaScript however my PHP skills are little to none.
I am creating an application for my final year project at University
what displays football rumours posted by different users. My problem
is as follows:
I have one screen that displays each individual rumour, using a while
loop in PHP I am able to get each rumour from the database and display
them correctly. However I want to be able to click on one rumour which
then displays this rumour in a different screen, along with options to
reply/share etc. However I do not know how to tell which rumour has
been clicked on.
Snippets of my code:
All rumours page:
<?php
$q1 = "SELECT * FROM tblrumours;";
$r1 = mysql_query($q1);
while( $row1 = mysql_fetch_assoc($r1) ){
?>
<a class="rumourTag submit" id="<?php echo $row1['rumourID']; ?>">
<div class='oneRumour'>
<div class='standardBubble'>
<p>
<?php
$userID = $row1['userID'];
$q2 = "SELECT * FROM tblusers WHERE userID = $userID;";
$r2 = mysql_query($q2);
while( $row2 = mysql_fetch_array($r2) ){
$username = $row2['username'];
$teamID = $row2['teamID'];
}
$q5 = "SELECT * FROM tblteams WHERE teamID = $teamID;";
$r5 = mysql_query($q5);
while( $row5 = mysql_fetch_array($r5) ){
echo "<img src='img/".$row5['teamPicture']."' alt=''
class='teamImg' />";
}
?>
<span class='username'>
<?php
echo $username;
?>
</span>
<br/>
<span class='rumourMsg'><?php echo $row1['rumourText']; ?></
span>
</p>
</div>
</a>
SINGLE RUMOURS PAGE:
<?php
$q1 = "SELECT * FROM tblrumours WHERE rumourID = 1;"; /* NEED
TO SELECT WHERE RUMOUR ID IS THE ONE THAT IS CLICKED */
$r1 = mysql_query($q1);
while( $row1 = mysql_fetch_array($r1) ){
?>..........
I have tried using Session variables, storing the ID's in an array,
creating a separate php file for the single rumour page, and all to no
avail. I am guessing I have to use AJAX in some way, but I have no
idea where to even begin. Any help is greatly appreciated!
Thanks!
If you need to click on a rumour to see more details about it, you could always output in the HTML a unique value used to reference that rumour in the DB.
e.g. have <span class='rumourMsg' id='rumourName'> where rumourName is a unique value stored in your database to reference that rumour. Then when a user clicks to see more details, you can make a request to the PHP page with that value and return the content.
e.g. rumourDetails?rumourName=uniqueRumourName
(make sure to escape all your data properly to avoid SQL injection vulnerabilities.)