How to create a series of DIVs using PHP + mySQL? - php

I'm looking to create a formatted product list from an SQL database. My aim is to have a store on my website with a series of small boxes containing some shorthand information about each product, that when clicked will open a pop-up containing detailed information. (I have a working Javascript/JQuery code to create the pop-ups.)
Here is the PHP code so far, simply to get the information from the database and display it on a webpage...
(I've been using XAMPP to provide an environment for me to test the code in)
<?php
mysql_connect("localhost", "root", "") or die (mysql_error ());
mysql_select_db("Database1") or die(mysql_error());
$strSQL = "SELECT * FROM Products";
$rs = mysql_query($strSQL);
while($row = mysql_fetch_array($rs)) {
echo $row['Brand'] . " " . $row['ProductName'] . " " . $row['Image'] . "<br />";
}
mysql_close();
?>
I want the echoed line to be displayed in a divider, with a divider generated for each record in the SQL database (say I have 10 products available, there would be ten dividers, and 10 different boxes on the webpage). The divider's class is "ProductBox".
echo "<div class=\"ProductBox\">"; $row['Brand'] . " " . $row['ProductName'] . " " . $row['Image'] . "</div>";
This was the closest I have come to a solution, which was simply managing to write a code with no syntax errors - alas, nothing actually displays on the webpage.
If I'm going about this entirely the wrong way please tell me - I'm fairly sure I need to use a SQL database to dynamically update stock on a live website, but if I need to implement a different programming language or whatever then just tell me what you think would work and help me with a solution.

You have an extra semicolon in your code
echo "<div class=\"ProductBox\">"; $row['Brand'] . " " . $row['ProductName'] . " " . $row['Image'] . "</div>";
Replace with
echo "<div class=\"ProductBox\">". $row['Brand'] . " " . $row['ProductName'] . " " . $row['Image'] . "</div>";

mysql_fetch_array needs to be used like this (see PHP Doc):
while($row = mysql_fetch_array($rs, MYSQL_ASSOC)) {
}
or you could just use "mysql_fetch_assoc" instead.
HOWEVER, if you're new to PHP, I HIGHLY RECOMMEND that you get started on the right foot. mysql_query functions are soon to be deprecated. DON'T USE THEM. Most recommend using "PDO" for querying your database. Here's a great tutorial to teach you: http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers
Also, as mentioned, you have an extra semi-colon.

Dont forget these basics markups :
`<HTML>
<HEAD>
</HEAD>
<BODY> put in here your divs
</BODY>
</HTML>`

Related

Teamspeak 3 Framework

I'm trying to get all clients database id, but I've been unable to using foreach etc as it always returns the value as NULL.
I need to get a foreach with the database ids and put it in an array
$userchannel = $clients->cid->clientList["client_database_id"];
After some fiddling i managed to get this to work, please verifiy. If you have questions regarding the code. Feel free to ask them.
What i've done in basic is modifing the existed code from the examples shown in the teamspeak php framework site. I used the Android user list for the most code. From there on its just trying and debugging ;)
this code will print the database id of the user together with the username. (Ofcourse from this point you can do everything you want with it.)
Also, maybe take a quick look at the api documentation for the php framework. It has alot of useful coding tips and tricks.
https://docs.planetteamspeak.com/ts3/php/framework/
edit (07-01-17)
Something I also noticed, make sure the query user has enough rights, for ease I made mine server admin query (grants access to all options, Please be aware that this could be insecure in a active site!)
<?php
// load framework files
require_once("libraries/TeamSpeak3/TeamSpeak3.php");
try {
// connect to local server, authenticate and spawn an object for the virtual server on port 9988
$ts3_ServerInstance = TeamSpeak3::factory("serverquery://###:#######:##/?server_port=9987");
$selected_sid = $ts3_ServerInstance->serverList();
$ts3_VirtualServer = $ts3_ServerInstance->serverGetById($selected_sid);
/* walk through list of clients */
echo "<table class=\"list\">\n";
echo "<tr>\n" .
" <th>DB id</th>\n" .
" <th>Nickname</th>\n" .
"</tr>\n";
foreach($ts3_VirtualServer->clientList() as $client) {
echo "<tr>\n" .
" <td>" . $client['client_database_id'] . "</td>" .
" <td>" . htmlspecialchars($client) . "</td>" .
"</tr>\n";
}
echo "</table>\n";
}
catch(Exception $e) {
/* catch exceptions and display error message if anything went wrong */
echo "<span class='error'><b>Error " . $e->getCode() . ":</b> " . $e->getMessage() . "</span>\n";
}
I managed to fix it.
$ts3_VirtualServer->channelGetById(152) // 152 is the channel ID

mysqli dynamic generated table with link that opens form with all values from row

I have this table:(megaoverzicht.php) (I left out the part where it connects to the db)
echo "<table border='1'><tr><th>Formulier Id</th><th>Domeinnaam</th><th>Bedrijfsnaam</th><th>Datum</th><th>Periode</th><th>Subtotaal</th><th>Dealernaam</th><th>Offerte Maken</th></tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['formuliernummer'] . "</td>";
echo "<td>" . $row['domeinnaam'] . "</td>";
echo "<td>" . $row['bedrijfsnaam'] . "</td>";
echo "<td>" . $row['datum'] . "</td>";
echo "<td>" . $row['periode'] . "</td>";
echo "<td> € " . $row['subtotaal'] . "</td>";
echo "<td>" . $row['dealercontactpersoon'] . "</td>";
echo "<td><a href='offertemaken.php?id=" . $row->id . "'>Offerte Maken </a></td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
I want to open offertemaken.php when the user clicks on Offerte Maken. It needs to open the form with the data from that row(id).
This is the code from (offertemaken.php)(I left out the part where it connects to the db)
<?php
$id=$_POST['id'];
$data = 'SELECT * FROM cypg8_overzicht WHERE id="$id"';
$query = mysqli_query($con,$data) or die("Couldn't execute query. ". mysqli_error());
$data2 = mysqli_fetch_array($query);
?>
<form>
<div class="formcontainer" onmousemove="">
<input type="text" name="datum" id="datum" value="<?php echo $data2[datum]?>">
<input type="text" name="formuliernummer" id="formuliernummer" value="<?php echo $data2[formuliernummer]?>">
<input type="text" name="periode" id="periode" value="<?php echo $data2[periode]?>">
<input type="text" name="domeinnaam" id="domeinnaam" value="<?php echo $data2[domeinnaam]?>">
<input type="text" name="bedrijfsnaam" id="bedrijfsnaam" value="<?php echo $data2[bedrijfsnaam]?>">
<input type="text" name="dealercontactpersoon" id="dealercontactpersoon" value="<?php echo $data2[dealercontactpersoon]?>">
</div><!--/.formcontainer-->
</form>
I cant get it to work. I am missing something I think! I make an error in the codes below:
echo "<td><a href='offertemaken.php?id=" . $row->id . "'>Offerte Maken </a></td>";
$id=$_POST['id'];
$data = 'SELECT * FROM cypg8_overzicht WHERE id="$id"';
I have been looking at a lot of tutorials but cant understand what i am doing wrong. Here a list to show that i am not just asking but actually have been looking for a solution by myself.
http://www.daniweb.com/web-development/php/threads/341921/-php-mysqli-update-database-using-id-syntax-help-requested-
http://www.codeofaninja.com/2012/01/phpmysqli-update-record.html
I have looked at many more but i don’t want to bother all of you with an extreme long list of links. And i am not allowed because my rep is not big enough! Dont downvote me please!
Question
I want to open offertemaken.php when the user clicks on Offerte Maken. It needs to open the form with the data from that row(id)?
Edit 1 Getting closer to the endresult
I found out(thanks to Cuba32) that the link in megaoverzicht.php was doing nothing so i changed the following
<a href='offertemaken.php?id=" . $row->id . "'>
to
<a href='offertemaken.php?id=" . $row['id'] . "'>
Now it is creating these kind of links:
something/formulieren/overzichten/offertemaken.php?id=24
This is a good thing(i think) but the form that opens is blank so offertemaken.php is doing nothing with the id???
Edit 2 (Thanks to Cube32)
Since yesterday the code has changed quite a bit. I belive that megaoverzicht.php is finished it sends the link as described in edit 1. The only problem is know in offertemaken.php. Below i will put in the code.
$con = mysqli_connect($server,$username,$password,$database);
if (!$con){
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,$database);
$id=$_GET['id'];
if($data = mysqli_prepare($con, 'SELECT * FROM cypg8_overzicht WHERE id="?"'))
{
/* bind parameters for markers */
mysqli_stmt_bind_param($data, "s", $id);
/* execute query */
mysqli_stmt_execute($data);
$data2 = mysqli_stmt_fetch($data);
But this code gives me the following error.
Warning: mysqli_stmt_bind_param(): Number of variables doesn't match number of parameters in prepared statement in line 31. Line 31:
mysqli_stmt_bind_param($data, "s", $id);
I dont know how to solve this part. I will offcourse be looking on the internet to try and find a solution but if anyone knows it please post it. Thanks in advance.
Edit 3<= No more error (Thanks to Your Common Sense)
by changing WHERE id="?"' into WHERE id=?' i no longer have the error. But still it is not showing anything in the input fields
Edit 4<= Getting to confused and going back to original code.
Thanks for everyone who got me so far. But I can't see the forest anymore through the trees. I am going back to the original code and try to solve that. So the code is now as follows:
$id=$_GET['id'];
$data = 'SELECT * FROM cypg8_overzicht WHERE id="$id"';
$query = mysqli_query($con,$data) or die("Couldn't execute query. ". mysqli_error());
$data2 = mysqli_fetch_array($query);
error_reporting(E_ALL);
But this gives the following errors inside the input fields:
Notice: Use of undefined constant formuliernummer - assumed 'formuliernummer' in offertemaken.php on line 37
This error goes for all the input fields.
Edit 5
Fixed this by changing <?php echo $data2[formuliernummer]?> to <?php echo $data2['formuliernummer']?> but it is still not showing the information.
Edit 6 THE SOLUTION
I added the answer to the question below. Just look for answer written by HennySmafter.
Thanks to:
Cube32, SITDGNymall, Your Common Sense. Thanks all of you for helping me find the solution.
It took me a while but i found the answer.
megaoverzicht.php
echo "<td><a href='offertemaken.php?id=" . $row['id'] . "'>Offerte Maken </a></td>";
offertemaken.php
// Check whether the value for id is transmitted
if (isset($_GET['id'])) {
// Put the value in a separate variable
$id = $_GET['id'];
// Query the database for the details of the chosen id
$result = mysqli_query($con,"SELECT * FROM cypg8_overzicht WHERE id = $id");
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = "Invalid query: " . mysqli_error($result) . "\n";
$message .= "Whole query: " . $query;
die($message);
}
// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(),etc.
while ($row = mysqli_fetch_assoc($result)) {
echo $row['formuliernummer'] . "\n";
echo $row['domeinnaam'] . "\n";
echo $row['bedrijfsnaam'] . "\n";
echo $row['datum'] . "\n";
echo $row['periode'] . "\n";
}
} else {
die("No valid id specified!");
}
It is not showing the values in the input boxes because there are no input boxes into the echo but those can be easily added I imagine.
In reference to the edit 1:
You are referencing the variables by association, but are outputing the mysql as a default array. instead of
$data2 = mysqli_fetch_array($query);
Try this:
$data2 = mysqli_fetch_assoc($query);
Or:
$data2 = mysqli_fetch_array($query, MYSQLI_ASSOC);
Also, do you have error reporting turned on? If so, then if the array contains no data you should be getting warnings of some kind. If not, a good test is:
error_reporting(E_ALL);
This will warn you about any places where a variable is unset or a array is empty. Another good test is to simply echo out your query, which will tell you if there's any errors in the query itself(which can save some time). If you're not going to go the Prepared Statements route(which is highly encouraged), you can simply echo out $data into your script.

PHP/MySQL - Unable to INSERT INTO database

I posted a couple days ago and I could not insert an additional record into a MySQL database I setup. I corrected the syntax, but the database will not update again. Basically, I have a couple forms in HTML that carry sessions over to the next pages until the PHP is processes on the final page to INSERT into the database. It worked twice (I have 2 records in the database now), but it won't insert any additional records. It worked fine a couple days ago. The only changes I made to anything was that I added a search feature that accesses the same database with the same user, but the connection is closed at the end of that script as well. Here is the code I am using to INSERT into the database (I know it isn't the best coding job, I'm still learning).
<?php
$con = mysql_connect("localhost","my_username","mypassword");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("dgibbo1_imaging", $con);
// Here too, please mysql_real_escape_string() all parameters
mysql_query("INSERT INTO imaging (os,MAC,Model,AntiVirus,Browser,Email,Connectivity,Sound,Ports) VALUES ('".$_SESSION['imaging2']."','".$_SESSION['imaging3']."','".$_SESSION['imaging4']."','".$_SESSION['antivirus']."','".$_SESSION['browser']."','".$_SESSION['email']."','".$_SESSION['connectivity']."','".$_SESSION['sound']."','".$_SESSION['ports']."')");
OR die("Could not update: ".mysql_error());
mysql_close($con);
?>
The name of the database is imaging. The columns are setup as:
id (This is the primary key field)
os
MAC
Model
AntiVirus
Browser
Email
Connectivity
Sound
Ports
I just find it odd that it inserted records without any problems until I tried it again today. Is it possible that it has something to do with my code for the search?
The search is a simple form on another page and processes this form:
<?php
$con = mysql_connect("localhost","my_user","mypassword");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("dgibbo1_imaging", $con);
// Always escape parameters injected into SQL queries
$result = mysql_query( "SELECT * FROM imaging WHERE MAC LIKE '%"
. mysql_real_escape_string ( $search, $con )
. "%'"
);
echo "<table border='1'>
<tr>
<th>MAC</th>
<th>Model</th>
<th>AntiVirus</th>
<th>Email</th>
<th>Browser</th>
<th>Connectivity</th>
<th>Sound</th>
<th>Ports</th>
</tr>";
while($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['MAC'] . "</td>";
echo "<td>" . $row['Model'] . "</td>";
echo "<td>" . $row['AntiVirus'] . "</td>";
echo "<td>" . $row['Email'] . "</td>";
echo "<td>" . $row['Browser'] . "</td>";
echo "<td>" . $row['Connectivity'] . "</td>";
echo "<td>" . $row['Sound'] . "</td>";
echo "<td>" . $row['Ports'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
Meanwhile, the search will pull up the 2 existing records successfully every time, but I can't add new records and I'm wondering if it has something to do with this.
Thanks for any suggestions. I know my syntax probably isn't the best, so any suggestions from this site are always appreciated.
Try creating a separate php file and hard coding the values into it. Run that and see what happens. your search form shouldnt interfere with another form.
edit any errors when using the form? any errors when inserting to another table?
I saw your post, and it all looks "right". What I'd suggest is to add some logging instead of DIE and look at what MySQL is saying about those insert statements:
$sql = "INSERT INTO imaging ....";
mysql_query($sql);
if(mysql_errno()) {
$message = mysql_error() . "\n" . $sql . "\n";
$fp = fopen('c:\mylogifle.txt', 'a');
fwrite($fp, $message);
fclose($fp);
}
AND...as everyone has mentioned, encode those strings - assuming that the SQL is actually being executed, and you "know" it works, there's a very high possibility that some punctuation in one of the values is interfering with the SQL, like an unexpected comma somewhere that confuses MySQL

Combine $_GET and $_POST in PHP?

for some friends and family (different sites), I created a script that allows them to input data into the database. With
echo ("<a href=\"./pagina.php?ID=" . $row['ID'] . "\">" . $row['ID'] . "<br>");
, I 'send' the ID of the requested table to the URL.
In pagina.php, I have this code:
ID: <?php echo $_GET["ID"]; ?>
That works, of course, but now I want to use that ID to also display the data from the database, so not from the URL. These values are " . $row['onderwerp'] . " and " . $row['tekst'] . "
(There may be more values to come, but I'm just a beginner, trying to get something to work).
I know this is possible, but I just can't get anything to work, as I have just started learning PHP.
I hope you can help me.
If you don't care whether data came from a $_COOKIE, $_GET, or $_POST, you can use $_REQUEST.
$id = (int)$_GET['id'];
$sql = "SELECT onderwerp, tekst FROM yourtable WHERE id=$id";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
echo "{$row['onderwerp']} - {$row['tekst']}<br />";
}

Fetching queries from MySQL and printing it in a javascript calendar

I have a hardcoded javascript calendar and I need to print the events from my database which is a PHP MySQL server side database. But I'm not sure how to fetch the queries from mysql and print it into the javascript calendar :/ I found something that makes use of VBSCRIPT but its very confusing :/
The general outline:
Use PHP to access the database and fetch rows of calendar data (using a query). Then, print it out to a Javascript data structure like JSON or native Javascript that is loaded into the browser. Then, work with the Javascript calendar code to load the data into the view the browser presents to the user on the webpage.
There's a lot of variation that can occur here, but roughly (in semi-psuedo code):
Within page contains the calendar (outputs in JSON notation)
<script type="text/javascript">
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$result = mysql_query('SELECT * FROM Events', $link);
$count = 0;
echo "var events = {";
while ($row = mysql_fetch_assoc($result)) {
if ($count !== 0) echo ",";
echo "{";
echo "'eventid':'" . add_slashes($row['eventid']) . "',";
echo "'title':'" . add_slashes($row['title']) . "',";
echo "'description':'" . add_slashes($row['description']) . "',";
echo "'date':'" . add_slashes($row['date']) . "',";
echo "'time':'" . add_slashes($row['time']) . "'";
echo "}";
count++;
}
echo "};";
?>
$calendar = new Calendar(events);
</script>
Of course, there are a number of ways that this could be done, but this is one way it could flow. This is only an example; dropping this code into a PHP page on a server will not work, it's only meant to demonstrate how in general it could flow.

Categories