still getting my feet wet with php and mysqli, have so much to learn, but at this point this question is one of my most important priorities.
I did some research about this issue but am currently overwhelmed by pretty sophisticated stuff for my level, to be honest. I'd like to find the simplest most efficient way to "automatically" generate a great number of pages each with varying data in it.
the example of page 1's code below is extremely simplified, because the actual page actually has a lot more stuff, but the simplified example serves, I hope, to make my point.
<?php
$servername = "servername";
$username = "username";
$password = "password";
$db= "db";
$conn = mysqli_connect("servername","username","password","db");
$query = "SELECT word FROM demo WHERE group=1";
$result = $conn->query($query);
$row = mysqli_fetch_assoc($result);
$word = $row['word'];
echo $word;
?>
in my table I have / would have something like 500 entries (records?) in the 'group' column, numbered 1, 2, 3 etc all the way to 500.
for my specific purpose, I absolutely need to create as many online pages as there are groups -- in this example, 500 pages.
page 2's echo would have to refer to group 2, page 3's echo would have to refer to group 3, and so on.
obviously, there's a way to do this without copying and pasting the code 500 times and manually changing the group in each! haha. but what's the simplest way?
thank you in advance for any understanding and help, and either way, have an awesome day.
If I'm understanding you correctly, I believe you're waiting to create pages from the database Dynamically. You can use a get variable in the request http://yoursite.com/page.php?group=1.
Then in your code update your query to do:
$query = "SELECT word FROM demo WHERE group=".$_GET['group'];
That query is insecure, as any user could inject raw mysql into the $_GET['group'] variable.
$group = mysqli_real_escape_string($conn, $_GET['group']);
$query = "SELECT word FROM demo WHERE `group`='$group'";
This is much safer.
So PHP will look for a file called index.php by default in any directory that it accesses. You can place such a file in the root of public_html or www or where ever your site accesses. Now in this file you can do something like:
<?php
if($_GET['group']){ //Make sure you have the var
$query = "SELECT word FROM demo WHERE `group`=?"; //The query with param
if ($stmt = mysqli_prepare($conn, query){ // try it out
mysqli_stmt_bind_param($stmt, "i", $_GET['group']); // bind the data
$stmt->execute(); //run it
$result = $stmt->get_result(); // get results
//use result to echo and stuff
}
} else {
//Do something incase there is not a group specified.
echo "Nothing here";
}
?>
Now when you go to your site you will get something like 'localhost/index.php' and see Nothing here but if you type localhost/index.php?group='55' you will have access to the page 55 data in result.
Related
I am in a little bit in doubt, if I am on the correct path here. I have a mysql database, where I have login details of users. I am making a profile page, where I would like the informations on a user is shown to the user. I am now trying to return the firstname there is a column in the database. Am I on the correct path with this code?
<td>
Firstname
<?php
$stmt = $mysqli->prepare("SELECT firstname FROM login");
$stmt->execute();
$fname = null;
$stmt->bind_result( $fname);
while($stmt->fetch()) {
$firstname = // Code here
echo $firstname;
}
$stmt->close();
$mysqli->close();
?>
</td>
Update:
I tried to make the code a little bit smaller. This code actually retrives users, but it is all the users in the database, and not only the user I am logged into with. Should the SELECT query be asigned with the primarykey, if I only need the firstname on the current user I am logged in as?
<td>
Firstname
<?php
$sql ="SELECT firstname FROM login;";
$res = $mysqli->query($sql);
//print($res);
if($res){
while($row = $res->fetch_assoc()){
echo $row['firstname'];
}
}
?>
</td>
You are on the correct path but you need to assign your array to a variable so you can print adding your column name in the scope and remove the bind of $fname
//$stmt->bind_result($fname);
while($column = $stmt->fetch()) {
$firstname = $column['firstname'];
echo $firstname;
}
Or you can just use the variable you bind before
$stmt->bind_result($fname);
while($stmt->fetch()) {
echo $fname;
}
You could optimize your query and limit tresult to only one user by adding a WHERE condition to your query, you can use user ID for example
SELECT firstname FROM login WHERE userid = 1
If you're playing around with PHP and trying to learn how things work, you're on a great path. If you're planning on deploying this code to the internet, you have a few issues:
Your markup seems off. Why are you putting all of the first names in a single <td>?
You shouldn't have a SQL query happening inside of a markup. What if you want to show results from a cache or a text file some day? Ideally you wouldn't even mix PHP and HTML. Some folks use PHP's built-in templating abilities, but it's generally preferred to use a template language like jade or twig.
Your code alignment isn't consistent.
But if you're just seeing what PHP can do, good job. Keep trying stuff out. It's the best way to learn for most people. Others like reading a book, then trying stuff.
I have created a website which gets data from two 'different' MySql database tables. The tables have identical layouts (so the numbers in each table differs but 100% similar in ID's and column names). Now I am a complete self-made programming noob so bear with me in the following.
On the websites front page I display some data from both of the two tables. The way I do this is by creating a variable ($tableName) that holds the name of the table I need. This variable is then used for generating the necessary data in another file (data.php) and then displaying that data on the front page by the file design.php. This process is replicated for all tables in the MySql database. (below is a very simplified format).
Frontpage.php:
<?php
include('../connection.php');
?>
<?php
$tableName = table1;
include('../Data.php');
include('../Design.php');
?>
<?php
$tableName = table2;
include('../Data.php');
include('../Design.php');
?>
.....(etc.)
Data.php:
$query = "SELECT * FROM {$tableName} WHERE ID = 1";
$result = mysqli_query($conn, $query) or die('error');
while($data = mysqli_fetch_array($result)) {
For ($n = 0; $n < 1; $n++){
$dataVariable = $data["columnname"];
}
}
Design.php
<?php echo $dataVariable; ?>
So what happens is that the user goes to the $dataVariable link and is then sent to Ultimate.php which also includes the Data.php file in order to display a hell-uv-alot of data. I therefore have to again declare the $tableName variable in the Ultimate.php file and then duplicate the Ultimate.php file for every single table there is in the MySql database and change href-link in the Design.php file. (very annoying).
My question is: how can I pass on my $tableName variable from the href on the front page to Ultimate.php? I have searched on here and found a way which includes $tableName to the URL opened on Ultimate.php whereafter I use $_GET inside Ultimate.php to collect it. For some reason I couldn't make that work - and i don't know if this is at all a solid way to solve things in my case.
More importantly: I have never worked with programming before so if anyone can advise me whether I am setting this up most efficiently or not that would also be great! I very much welcome links to guides/tutorials which you think might benefit me at this point!
Thanks a lot in advance!
<?php echo $dataVariable; ?>
Then at the top of Ultimate.php:
<?php
$var = $_GET['var'];
?>
This takes the variable off the browser
http://www.example.com/Ultimate.php?var=yourvariable
You can pass variables from a hyperlink to another page using GET.
hyperlink text
$_GET['key']
http://php.net/manual/en/reserved.variables.get.php#refsect1-reserved.variables.get-examples
These two pull out data from two different data bases. It's all good undtil I repeat the first one for a second time (to pull out the count of comments of more than one article), the second script (pulls out the data about vistis to the articles and arranges them by desc. order) stops working (no error, nothing, just doesn't provide an output). I'm no expert (yet) in the PHP so I can't seem to figure what is wrong in this sutuation. Maybe some of you will notice some obvious flaw which makes 'em interfere like that?
1st script (comment count). Just to make it clear: I don't use "define", the second time I use it for a diff. article. It's needed just in the first one to work.):
<?php
$id = "1"; //The ID of the page. You can get this from Manage -> Pages.
define('IN_COMMENTICS', '1');
require ($_SERVER['DOCUMENT_ROOT'].'comments/includes/db/connect.php');
$query = mysql_query("SELECT * FROM `".$cmtx_mysql_table_prefix."comments` WHERE is_approved = '1' AND page_id = '$id'");
$total = mysql_num_rows($query);
echo $total;
?>
Second script (counts visits):
<?php
$sql = "SELECT pagename, hits, title FROM counts ORDER BY hits DESC LIMIT 10";
$res = mysql_query($sql);
if(!$res) {
// oops - exit?
}
while(list($page,$hits,$title) = mysql_fetch_row($res)) {
echo "<li><a href='$page'>$title</a> $hits</li>";
}
?>
The only thing I could see is that you are using the function require to include you database initializing file, AND its executed two times which my create problems to causing this issue you are facing.
Perhaps, consider using require_once function which will take care to not load the database initializing file more than one time.
To conclude, I would suggest to do the following
Replace this:
require ($_SERVER['DOCUMENT_ROOT'].'comments/includes/db/connect.php');
by this:
require_once ($_SERVER['DOCUMENT_ROOT'].'comments/includes/db/connect.php');
I put together a simple script that pulls the product name, category name and product id from two tables. Then I take that data and use it to create a page title that's better than what I currently have for SEO purposes. For some reason I didn't think it would take as long as it's taking to run. There are 7k products.
My hosting company does allow the creation of a custom php.ini so I was able to override the 30 second time limit and changed it to 6000. But still the script times out. So I thought my script my suck. :)
Below is the script. Is there a better way I could write this so it doesn't time out? Or is what I'm trying to do just going to take some time and I need to write the script to do one category at a time?
<?php
// Make a MySQL Connection
mysql_connect("localhost", "myusername", "mypassword") or die(mysql_error());
mysql_select_db("mydatabase") or die(mysql_error());
$result = mysql_query("SELECT isc_products.prodcode, isc_products.prodname, isc_categories.catname FROM isc_products, isc_categories WHERE isc_products.prodcatids = isc_categories.categoryid")
or die(mysql_error());
while($row = mysql_fetch_array($result)){
$pname = mysql_real_escape_string($row['prodname']);
$catname = mysql_real_escape_string($row['catname']);
$sitename = Sitename;
$prodcode = $row['prodcode'];
$result2 = mysql_query("UPDATE isc_products SET prodpagetitle = '$pname - $catname - $sitename' WHERE prodcode = '$prodcode'")
or die(mysql_error());
}
?>
indexes http://www.threewestcreative.com/indexes.jpg
Thanks, your help is appreciated. :)
Thanks SO much everyone! I really appreciate the quick responses. I can't believe I overlooked something so simple as running a direct query against the database (without php). Geez... Thanks again!
Just run
UPDATE isc_products
INNER JOIN isc_categories ON isc_products.prodcatids = isc_categories.categoryid
SET isc_products.prodpagetitle=CONCAT(isc_products.prodname,' - ',isc_categories.catname,' - $sitename');
If it times out, your DB is fishy (missing indices?)
You can just use one query to do what you want.
UPDATE ssc_products, isc_categories
SET psc_products.prodpagetitle = CONCAT_WS(' - ', isc_products.prodname, isc_categories.catname, $sitename)
WHERE isc_products.prodcatids = isc_categories.categoryid;
Can you show your tables(s) structure? Its important when dealing with that many products, indexing is key. Also (while) loop is bad here, it will effect performance. Like the guys mention above 1 query should do the trick.
I'm not sure why you're doing this in PHP, given that you could achieve this with a single UPDATE. Perhaps you've left out bits that do things like identify which records have already been changed?
So I'll assume you really do want to do this in PHP, and that you just want to run this script once in order to update the prodpagetitle field table-wide.
One option would be to split this into separate scripts. Have a main script that does the SELECT, then skips through the UPDATEs by calling a second script, with the data to use in variables in the GET. For example:
<?php
// Make a MySQL Connection
mysql_connect("localhost", "myusername", "mypassword") or die(mysql_error());
mysql_select_db("mydatabase") or die(mysql_error());
$result = mysql_query("SELECT isc_products.prodcode, isc_products.prodname, isc_categories.catname FROM isc_products, isc_categories WHERE isc_products.prodcatids = isc_categories.categoryid")
or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$pname = mysql_real_escape_string($row['prodname']);
$catname = mysql_real_escape_string($row['catname']);
$sitename = Sitename;
$title=sprintf("%s - %s - %s", $pname, $catname, $sitename);
$url=sprintf("http://example.com/update.php?pcode=%s&title=%s", $row['prodcode'], $title);
$junk=file_get_contents($url)
}
?>
and:
<?php
// This is update.php, called by the script above.
mysql_connect("localhost", "myusername", "mypassword") or die(mysql_error());
mysql_select_db("mydatabase") or die(mysql_error());
$qfmt="UPDATE isc_products SET prodpagetitle = '%s' WHERE prodcode='%s'";
mysql_query(sprintf($qfmt, $_GET['pcode'], urldecode($_GET['title']));
?>
Node that this should be considered EXAMPLE code. I haven't tested it and don't plan to. You probably want to include some facility to mark your already-changed fields, so that you can continue on from whence you left off if the new script also times out (which it probably will). This script contains vulnerabilities, and should only be run in a secure environment or with significant modification to make it safe. </fineprint>
Been trying this for quite a while now and I need help. Basically I have a PHP file that queries database and I want to change the query based on a logged in users name.
What happens on my site is that a user logs on with Twitter Oauth and I can display their details (twitter username etc.). I have a database which the user has added information to and I what I would like to happen is when the user logs in with Twitter Oauth, I could use jQuery to take the users username and update the mysql query to show only the results where the user_name = that particular users name.
At the moment the mysql query is:
"SELECT * FROM markers WHERE user_name = 'dave'"
I've tried something like:
"SELECT * FROM markers WHERE user_name = '$user_name'"
And elsewhere in the PHP file I have $user_name = $_POST['user_name'];. In a separate file (the one in which the user is redirected to after they log in through Twitter) I have some jQuery like this:
$(document).ready(function(){
$.post('phpsqlinfo_resultb.php',{user_name:"<?PHP echo $profile_name?>"})});
$profile_name has been defined earlier on that page.
I know i'm clearly doing something wrong, i'm still learning. Is there a way to achieve what I want using jQuery to post the users username to the PHP file to change the mysql query to display only the results related to the user that is logged in. I've included the PHP file with the query below:
<?php
// create a new XML document
//$doc = domxml_new_doc('1.0');
$doc = new DomDocument('1.0');
//$root = $doc->create_element('markers');
//$root = $doc->append_child($root);
$root = $doc->createElement('markers');
$root = $doc->appendChild($root);
$table_id = 'marker';
$user_name = $_POST['user_name'];
// Make a MySQL Connection
include("phpsqlinfo_addrow.php");
$result = mysql_query("SELECT * FROM markers WHERE user_name = '$user_name'")
or die(mysql_error());
// process one row at a time
//header("Content-type: text/xml");
header('Content-type: text/xml; charset=utf-8');
while($row = mysql_fetch_assoc($result)) {
// add node for each row
$occ = $doc->createElement($table_id);
$occ = $root->appendChild($occ);
$occ->setAttribute('lat', $row['lat']);
$occ->setAttribute('lng', $row['lng']);
$occ->setAttribute('type', $row['type']);
$occ->setAttribute('user_name', utf8_encode($row['user_name']));
$occ->setAttribute('name', utf8_encode($row['name']));
$occ->setAttribute('tweet', utf8_encode($row['tweet']));
$occ->setAttribute('image', utf8_encode($row['image']));
} // while
$xml_string = $doc->saveXML();
$user_name2->response;
echo $xml_string;
?>
This is for use with a google map mashup im trying to do. Many thanks if you can help me. If my question isn't clear enough, please say and i'll try to clarify for you. I'm sure this is a simple fix, i'm just relatively inexperienced to do it. Been at this for two days and i'm running out of time unfortunately.
At first, you should escape the $_POST you're inserting straight to the query:
'SELECT * FROM markers WHERE user_name = `' . mysql_real_escape_string($user_name) . '`';
As Erik suggests, don't throw out of the window the most useful warnings - most probably the answer will pop right ahead then.
But what I'm not quite sure about is the way your mashup works. It could get a lot easier if you just do all the stuff inside the php itself, omitting javascript at all. You might also want to check OAuth callbacks - should give you twitter id or user name.
There's nothing wrong with:
$result = mysql_query("SELECT * FROM markers WHERE user_name = '$user_name'");
Other then being ripe for SQL injection - it should work. You may want to try your query directly on the database and see if the results are what you expect.
I'd also recommend turning on error reporting during development. Add the following lines to the top of your document:
error_reporting(E_ALL);
ini_set("display_errors", 1);
and it will help you uncover many errors.