PHP - Php + Javascript + Mysql
I am implementing a site that will be pulling data from a MySQL server every 2 seconds and updating the page accordingly. I want to redraw charts using Google Chart API as this is happening. Overall I do not want to have the page refresh for the user.
How should I implement this (generally of course)? I don't think there is a way to do it all in javascript...since I need to access a remote database and all. Please let me know what advice you have. thanks! Similar TutorialsOk, I consider myself a dabbler in programming so bear with me. What I need to do sounds fairly simple, but I cannot figure it out. I have an html page. Inside is some basic html and some Javascript. The javascript basically generates a random value consisting of numbers and characters in: var = randomToken. The length of the random value generated is 11 characters on chrome and 19 on FF? I have no idea why the discrepancy between browsers, but that's not a problem. I'll look into that later. What I'm having trouble doing is right now, I need to take that random value that was generated by a javascript function and save it out to a database, so on the other end, when someone browses to another page, I need to retrieve the saved value from the database. I've looked at many examples but they always include a bunch of stuff I don't need, like tables, multiple stuff in the database, etc. All I need to do is be able to store a variable and later read it out of a database. The database just needs a field to store the random value. Nothing else is needed in the database (for now anyway). I know I need php, but i am super green at using it. I have a mysql database/table built with field: randomVar So in a nutshell: The starting html page needs to: Generate random value in Javascript. Save it in a variable. Done. Pass it to php Not Done Update the database randomVar with the random value Not Done Zero out the randomVar field in the database at some point. (when originator hits stop button or closes the page.) Not DoneAnother html page needs to: PHP Read the randomVar from the database; if > 0 use it Not Done If = 0, echo back some text to the html page....like "Try Later... Not Done Pass it to javascript Not DoneI am not looking for the exact code unless you want to supply it? :) Thanks, Ray
Hi, hope I have posted this in the right place, I have the following code which contains PHP and javascript, where both work on there own but when I try putting them together I keep getting errors: Code: [Select] <?php include 'config.php'; include 'opendb.php'; $var = 'Smith'; $query = "SELECT * FROM search_directory WHERE merchant LIKE \"%$var%\""; $result = mysql_query($query); $id = $row{"id"}; while($row = mysql_fetch_assoc($result)) { echo "Name: {$row['name']} <br>"; echo "Subject: {$row['title']} <br><br>"; } include 'closedb.php'; ?> <a href="javascript:;" onclick="document.getElementById('.....').style.display='block';window.open('http://www.google.co.uk');"><img src="../../graphics/Click here.png" border="0" /></a> <div id="....." style="display:none;"> ...your text here </div> What I have been trying to do is get $id variable from the php code to replace the '.....' in the javascript and div id. I have tried putting it into an echo statement which seemed to work with the div id but the brought up errors when i tried with the javascript. If anyone knows how to solve this it would be very much appreciated. Thanks in advance. Hello Everyone, I think this might be a bit of a challenge but its always worth getting some input for solutions. I'm using jqplot to create graphs from data held in a database. And im having trouble thinking of a way to lay the data out in an acceptable way. To plot a line the javascript takes a statement in this form: line1 = [['x-axis1'],y-axis1],['x-axis2',y-axis2] I'm running this query to get the data: <?php $query2 = "SELECT * FROM tracker WHERE username = '" . mysql_real_escape_string($usera) . "'"; $result = mysql_query($query2) or die('Error, query failed : ' . mysql_error()); while($row = mysql_fetch_assoc($result)) { $data[] = $row; } ?> This returns things like this: $data[0]['date'], $data[0]['reps'] $data[1]['date'], $data[1]['reps'] etc... Values are likely to be added or removed so I need to construct a loop of some kind to format it like this, line1 = [['{$data[0]['date']}',{$data[0]['reps']}],['{$data[1]['date']}',{$data[1]['reps']}],['{$data[2]['date']}'],{$data[2]['reps']}]]; Can someone point me in the right direction? Thanks in Advanced This is my website http://www.rahulkadukar.info/ As you can see I have the blue navigation bar on top and on mouse hover you can see a drop down menu. The contents of the drop down menu can change and I wanted to write a script that would populate the contents of the drop down menus. Which of these is a better option 1. Use JavaScript along with a text file and use JavaScript to populate the drop down 2. Use a SELECT in PHP to populate the drop down menu I am expecting that the 10 main columns would have at the most 20 entries each. This topic has been moved to Ajax Help. http://www.phpfreaks.com/forums/index.php?topic=347585.0 create table mimi (mimiId int(11) not null, mimiBody varchar(255) ); <?php //connecting to database include_once ('conn.php'); $sql ="SELECT mimiId, mimiBody FROM mimi"; $result = mysqli_query($conn, $sql ); $mimi = mysqli_fetch_assoc($result); $mimiId ='<span>No: '.$mimi['mimiId'].'</span>'; $mimiBody ='<p class="leading text-justify">'.$mimi['mimiBody'].'</p>'; ?> //what is next? i want to download pdf or text document after clicking button or link how to do that Hello everyone, Sorry if this has been answered but if it has I can't find it anywhere. So, from the begining then. Lets say I had a member table and in it I wanted to store what their top 3 interests are. Their$ row has all the usual things to identify them userID and password etc.. and I had a further 3 columns which were labled top3_1 top3_2 & top3_3 to put each of their interests in from a post form. If instead I wanted to store this data as a PHP Array instead (using 1 column instead of 3) is there a way to store it as readable data when you open the PHPmyadmin? At the moment all it says is array and when I call it back to the browser (say on a page where they could review and update their interests) it displays 'a' as top3_01 'r' as top3_02 and 'r' as top3_03 (in each putting what would be 'array' as it appears in the table if there were 5 results. Does anyone know what I mean? For example - If we had a form which collected the top 3 interests to put in a table called users, Code: [Select] <form action="back_to_same_page_for_processing.php" method="post" enctype="multipart/form-data"> <input name="top3_01" type="text" value="enter interest number 1 here" /> <input name="top3_02" type="text" value="enter interest number 2 here" /> <input name="top3_03" type="text" value="enter interest number 3 here" /> <input type="submit" name="update_button" value=" Save and Update! " /> </form> // If my quick code example for this form is not correct dont worry its not the point im getting at :) And they put 'bowling' in top3_01, 'running' in top3_02 and 'diving' in top3_03 and we catch that on the same page with some PHP at the top --> Code: [Select] if (isset($_POST)['update_button']) { $top3_01 = $_POST['top3_01']; // i.e, 'bowling' changing POST vars to local vars $top3_02 = $_POST['top3_02']; // i.e, 'running' $top3_03 = $_POST['top3_03']; // i.e, 'diving' With me so far? If I had a table which had 3 columns (1 for each interest) I could put something like - Code: [Select] include('connect_msql.php'); mysql_query("Select * FROM users WHERE id='$id' AND blah blah blah"); mysql_query("UPDATE users SET top3_01='$top3_01', top3_02='$top3_02', top3_03='$top3_03' WHERE id='$id'"); And hopefully if ive got it right, it will put them each in their own little column. Easy enough huh? But heres the thing, I want to put all these into an array to be stored in the 1 column (say called 'top3') and whats more have them clearly readable in PHPmyadmin and editable from there yet still be able to be called back an rendered on page when requested. Continuing the example then, assuming ive changed the table for the 'top3' column instead of individual colums, I could put something like this - Code: [Select] if (isset($_POST)['update_button']) { $top3_01 = $_POST['top3_01']; // i.e, 'bowling' changing POST vars to local vars $top3_02 = $_POST['top3_02']; // i.e, 'running' $top3_03 = $_POST['top3_03']; // i.e, 'diving' $top3_array = array($top3_01,$top3_02,$top3_03); include('connect_msql.php'); mysql_query("UPDATE members SET top3='$top3_array' WHERE id='$id' AND blah blah blah"); But it will appear in the column as 'Array' and when its called for using a query it will render the literal string. a r r in each field instead. Now I know you can use the 'serialize()' & 'unserialize()' funtcions but it makes the entry in the database practically unreadable. Is there a way to make it readable and editable without having to create a content management system? If so please let me know and I'll be your friend forever, lol, ok maybe not but I'd really appreciate the help anyways. The other thing is, If you can do this or something like it, how am I to add entries to that array to go back into the data base? I hope ive explained myself enough here, but if not say so and I'll have another go. Thanks very much people, L-PLate (P.s if I sort this out on my own ill post it all here) I have following piece of code below, and I would like to be able to express it pure SQL, something that could go into a .sql file :
$request_string='SELECT topic_forum_id FROM topic_table WHERE topic_id= 2014'; $query=database->prepare($request_string); $query->execute(); $data=$query->fetch(); $query->closeCursor(); $forum=$data['topic_forum_id']; $request_string='INSERT INTO post_table (post_topic,post_forum) VALUES (2014,:forum)'; $query=database->prepare($request_string); $query->bindValue(':forum',$forum,PDO::PARAM_INT); $query->execute(); $data=$query->fetch(); $query->closeCursor();Is it possible ? So i have this php as shown below. It should make a list of comments with comment replies below their comment respectively. The problem is that it only goes through and shows 1 comment and all the comment replies for that one comment. It should be showing all comments i have in the db for that article. If i remove the second while then it shows all the comments correctly but no comment replies then... How do i get this script to loop through the db for every comment but also loop through every comment reply for that $row[id]? If anyone has a better / more efficient way of what I am trying to do, please explain or show example (i am open to anything)... Code: [Select] // what article are we showing? $article_to_show_id = $_GET['article_id']; $active_is_set_text = "1"; // Active Column text that makes it okay to show // Finding the article $search_for_article = mysql_query("SELECT * FROM articles WHERE id = '$article_to_show_id' AND active = '$active_is_set_text'"); while($row = mysql_fetch_array($search_for_article)) { // format the last updated date right $update_date_edit = $row[update_date]; $update_date_edit = date('F j, Y \a\t h:ia', $update_date_edit); $row[update_date] = $update_date_edit; // format the submit updat date right $submit_date_edit = $row[submit_date]; $submit_date_edit = date('F j, Y \a\t h:ia', $submit_date_edit); $row[submit_date] = $submit_date_edit; echo ' <div> ', $row[title] ,' </div> <div> by: ', $row[author] ,' on ', $row[submit_date] ,' </div> <div> ', $row[content] ,' </div> <div> Last Updated: ', $row[update_date] ,' </div> <form action="article_reply.php" method="post"> <input type="hidden" name="article_id" value="', $row[id] ,'" /> <button name="article_reply" type="submit" value="submit">Reply</button> </form> '; } $comment_count = 0; $comment_reply_count = 0; // Finding all of the comments $search_for_article = mysql_query("SELECT * FROM article_comments WHERE article_id = '$article_to_show_id' AND reply_id = '0'"); while($row_comment = mysql_fetch_array($search_for_article)) { // format the submit updat date right $comment_date_edit = $row_comment[comment_date]; $comment_date_edit = date('F j, Y \a\t h:ia', $comment_date_edit); $row_comment[comment_date] = $comment_date_edit; echo ' <br> <br> COMMENT:<br> <div> By: ', $row_comment[username] ,' on ', $row_comment[comment_date] ,' </div> <div> ', $row_comment[comment] ,' </div> '; $comment_count++; // Finding all of the comment replies if any $search_for_article = mysql_query("SELECT * FROM article_comments WHERE article_id = '$article_to_show_id' AND reply_id = '$row_comment[id]'"); while($row_two = mysql_fetch_array($search_for_article)) { // format the submit updat date right $comment_date_edit = $row_two[comment_date]; $comment_date_edit = date('F j, Y \a\t h:ia', $comment_date_edit); $row_two[comment_date] = $comment_date_edit; echo ' <br> <br> COMMENT REPLY:<br> <div> By: ', $row_two[username] ,' on ', $row_two[comment_date] ,' </div> <div> ', $row_two[comment] ,' </div> '; $comment_reply_count++; } } Need some help I have 2 tables in a database and I need to search the first table and use the results from that search, to search another table, can this be done? and if it can how would you recommend that I go about it? Thanks For Your Help Guys! Hey guys I need some help for making some things work. This is my index.php and as you can see I have a table of my sql table and a drop list. Now when I press Add to chart on the table on my website, it goes to the cart. But when I select a item from the drop list and click on Add to chart, there only happens an increment of the quantity but the item does not go to the cart. http://fhcs.be/cart-demo2/index.php this is my website where you can check the problem out. Thanks Guys!!!! Code: [Select] <?php // Include MySQL class require_once('inc/mysql.class.php'); // Include database connection require_once('inc/global.inc.php'); // Include functions require_once('inc/functions.inc.php'); // Start the session session_start(); ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>PHP Shopping Cart Demo · Bookshop</title> <link rel="stylesheet" href="css/styles.css" /> </head> <body> <div id="shoppingcart"> <h1>Your Shopping Cart</h1> <?php echo writeShoppingCart(); ?> </div> <div id="booklist"> <h1>Books In Our Store</h1> <?php $sql = 'SELECT * FROM products ORDER BY id'; $result = $db->query($sql); $output[] = '<ul>'; while ($row = $result->fetch()) { $output[] = '<li>"'.$row['name'].': €'.$row['price'].'<br /><a href="cart.php?action=add&id='.$row['id'].'">Add to cart</a></li>'; } $output[] = '</ul>'; echo join('',$output); ?> <? $Link = mysql_connect("fhcs.be.mysql","fhcs_be","xxxx"); $Query = "SELECT * FROM products"; $DBName = "fhcs_be"; $results = mysql_db_query($DBName, $Query, $Link); ?> Select a name <select name = "drop1" size="1"> <Option Value=" ">Select One:</option> <? //Begins PHP for($u=0;$u<mysql_num_rows($results); $u++) { $ID=mysql_result($results,$u,'name'); ?> <option value="<? echo($ID); ?>"><? echo($ID); ?></option><? //Begins PHP //Begins PHP } ?> </select> <? //Begins PHP if (mysql_db_query ($DBName, $Query, $Link)) { } else { print ("FAILURE<BR>\n"); } mysql_close ($Link); ?> </div> </body> </html> I am having a bit of trouble here. I will explain what I am trying to do: I am trying to pull the Field Name: Account into my input form. My input form code looks like this: Code: [Select] Account Number: <input type="text" value="<?php echo($Account); ?>" name="Account"/> My PHP code above this looks like this: <?php @ $db = mysql_connect("localhost", "usr", "pass"); mysql_select_db("EmployeeInfo"); $sQuery = sprintf("SELECT * FROM EmployeeInfo WHERE EmployeeInfo.Name LIKE '%s'", mysql_real_escape_string($_POST['NameSelect'])); $result = mysql_query($sQuery); $actualResult = mysql_fetch_array($result); echo $actualResult['aSQLRow']; ?> My select query works properly. Can anyone find my error because I sure can't Thanks in advance, dmcdaniel Hi all! I am very new to php and mysql world so I could need some help. I found this UCP php code to control a database, where we could find various userinfo. I edited it and for unknown reasons everything else works except the change password. Here is the NewPassword.php: Code: [Select] <html> <body> <form action="Newpass.php" method="post"> <b><font size="4" color="#000080">Change your password! </font></b> <p>Old password <input type="password" name="P1" size="20" /> </p> <p>New Password <input type="password" name="P2" size="20" /></p> <p>Confirm New Password <input type="password" name="P3" size="20" /></p> <p> <input type="submit" /> <input type="reset" /> </p> <a href="Logged.php"">Go back</a> </form> </body> </html>And here is the Newpass.php Code: [Select] <?php session_start(); $pass1 = $_POST["P1"]; $pass2 = $_POST["P2"]; $pass3 = $_POST["P3"]; $escpass1 = mysql_real_escape_string($pass3); $escpass2 = mysql_real_escape_string($pass3); $escpass3 = mysql_real_escape_string($pass3); $user = $_SESSION['Username']; if(!isset($_SESSION['Username'])) { echo('You are not logged in!'); echo '<a href="index.php"">Go back</a>'; die; } $escuser = mysql_real_escape_string($user); include("database.php"); $query = "SELECT * FROM playerinfo WHERE user = '$escuser'"; $result = mysql_query($query); $row = mysql_fetch_row($result); if (!$con) { die('Could not connect: ' . mysql_error()); } $username_exist = mysql_num_rows($result); if($username_exist == 0) { echo('That username does not exist'); echo '<a href="NewPassword.php"">Go back</a>'; die; } if($escpass1 !== $row[1]) { echo("Wrong old password!"); echo '<a href="New Password.php"">Go back</a>'; die; } if($escpass2 !== $escpass3) { echo("Your new passwords do not match!"); echo '<a href="NewPassword.php"">Go back</a>'; die; } $query = "UPDATE playerinfo SET password = '$escpass3' WHERE user= '$escuser'"; $result = mysql_query($query); echo 'Password Changed!'; $_SESSION['Password'] = $escpass3; echo '<a href="Logged.php"">Go back</a>'; ?>And database.php Code: [Select] <?php $con = mysql_connect("edit","edit","edit"); mysql_select_db("edit"); //Remember that if you are using a external source, change the login info (mysql_connect(server[],user[],pass[]); ?>I edited the user/pw for obvious reasons. So the problem itself: Whatever I insert in password box I get this in return: Code: [Select] Warning: mysql_real_escape_string(): Access denied for user ''@'localhost' (using password: NO) in /home/crpnet/domains/c-rp.net/public_html/blankUCP/Newpass.php on line 6 Warning: mysql_real_escape_string(): A link to the server could not be established in /home/crpnet/domains/c-rp.net/public_html/blankUCP/Newpass.php on line 6 Warning: mysql_real_escape_string(): Access denied for user 'crpnet'@'localhost' (using password: NO) in /home/crpnet/domains/c-rp.net/public_html/blankUCP/Newpass.php on line 7 Warning: mysql_real_escape_string(): A link to the server could not be established in /home/crpnet/domains/c-rp.net/public_html/blankUCP/Newpass.php on line 7 Warning: mysql_real_escape_string(): Access denied for user 'crpnet'@'localhost' (using password: NO) in /home/crpnet/domains/c-rp.net/public_html/blankUCP/Newpass.php on line 8 Warning: mysql_real_escape_string(): A link to the server could not be established in /home/crpnet/domains/c-rp.net/public_html/blankUCP/Newpass.php on line 8 Warning: mysql_real_escape_string(): Access denied for user 'crpnet'@'localhost' (using password: NO) in /home/crpnet/domains/c-rp.net/public_html/blankUCP/Newpass.php on line 16 Warning: mysql_real_escape_string(): A link to the server could not be established in /home/crpnet/domains/c-rp.net/public_html/blankUCP/Newpass.php on line 16 That username does not existGo back I have a CVS file with about 1000 entries which I need to input into a MySQL database. Each line in the file has 5 fields but I am only interested in the first two. These are the description and name. I'm sure I can do this directly with MySQL but I need to use PHP anyway because there is actually other things I need to do with the data. I don't need to go into details because I already have that sorted. I just need to know how to open the CVS file and make a mysql insert loop with the data. Thanks Code: [Select] <?php $un = $_POST['Username']; // connect to the db $mysql_host = "localhost"; $mysql_database = "****"; $mysql_user = "*****"; $mysql_password = "*****"; $conn = mysql_connect($mysql_host,$mysql_user,$mysql_password); mysql_select_db($mysql_database,$conn); $query = "SELECT * FROM student WHERE Username='$un'"; $result = mysql_query($query); //Store all the course code into an array $course_code = mysql_fetch_array($result); //verification if(mysql_num_rows($result) == 1) { echo 1; // for correct login response $format = ".txt"; $output = $un.$format; $fh = fopen($output,'w') or die ("Can't open file"); for($num=1;$num<=5;$num++) { $code = $course_code['Course'.$num]; fwrite($fh,$code."\r\n"); } chmod($output,0777); //chmod the file to 0777 fclose($fh); } else { echo 0; // for incorrect login response } ?> im doing the Learning Management System application. this FirstTimeUser.php will connect to the database and list out the coursecode in .txt take a look at my code, the output is always 0. I already stuck on how to get 1. The connection for the php to mysql is correct. the username also exist in the database. is there any suggestion on how to debug it. i dont know, its like a simple coding, but its not working... please leave some suggestion... Umm.. Yeah, this MySQL line needs some reviewing list($total_banned_servers) = mysql_fetch_row(mysql_query("SELECT COUNT(id) FROM `toplist` WHERE banned='1' && serverowner=". $_SESSION['user'] ."")); in php you have the following mysql API fetch commands: ■mysql_fetch_array — Fetch a result row as an associative array, a numeric array, or both ■mysql_fetch_assoc — Fetch a result row as an associative array ■mysql_fetch_field — Get column information from a result and return as an object ■mysql_fetch_lengths — Get the length of each output in a result ■mysql_fetch_object — Fetch a result row as an object ■mysql_fetch_row — Get a result row as an enumerated array If u use one of them for example i use mysql_fetch_object. Code: [Select] $run = mysql_query(SELECT `status` FROM `[settings]` WHERE `name`= *); $display = mysql_fetch_object($run); other example Code: [Select] $run = mysql_query(SELECT `status` FROM `[settings]` WHERE `name`= 'abusing' AND `name`= 'hacking' AND `name`= 'cracking'); $display = mysql_fetch_object($run); When i do Code: [Select] $display->somethingIt wil assign the SELECT condition i want to assign the WHERE condition. the value of it. like i want to do this Code: [Select] $display->WHERE->hackinghow to do this? I have the code snippet below trying to check my database if a variable exists, it seems to work for the username but not for the email. The database name is "communitycouch_users" table is "reg_vars" to check the row: email. the variable $email is coming from my form. Upon form submission it will submit the data into the database regardless it exists. Code: [Select] $email= $_POST['email']; $username= $_POST['username']; // Check if the email and username exist already if(MysqlVarExists("communitycouch_users", "reg_vars", "email", $email) == true) { $errors_code["existing_email"] = "That email is already being used."; } if(MysqlVarExists("communitycouch_users", "reg_vars", "username", $username) == true) { $error_code["existing_username"] = "That username is already in use."; } Need help with php/sql. When I add a drink to the cart, only the quantity increases, but the item does not go to the cart. Check it out on my website http://fhcs.be/cart-demo2/ This is a part of my index.php <h1>Drinks</h1> <? $Link = mysql_connect("xxxx","xxxx","xxxx"); $Query = "SELECT * FROM products"; $DBName = "xxxx"; $results = mysql_db_query($DBName, $Query, $Link); ?> <select name = "drop1" size="1" id="drop1"> <Option Value=" ">Select Drink:</option> <? //Begins PHP for($u=0;$u<mysql_num_rows($results); $u++) { $id=mysql_result($results,$u,'name'); ?> <option value="<? echo($id); ?>"><? echo($id); ?></option><? //Begins PHP //Begins PHP } ?> </select> <? //Begins PHP if (mysql_db_query ($DBName, $Query, $Link)) { } else { print ("FAILURE<BR>\n"); } mysql_close ($Link); ?> <a href="cart.php?action=add&id='.$row['id'].'">Add to cart</a> //button to add to chart And this is a part of my cart.php <?php // Include MySQL class require_once('inc/mysql.class.php'); // Include database connection require_once('inc/global.inc.php'); // Include functions require_once('inc/functions.inc.php'); // Start the session session_start(); // Process actions $cart = $_SESSION['cart']; $action = $_GET['action']; switch ($action) { case 'add': if ($cart) { $cart .= ','.$_GET['id']; } else { $cart = $_GET['id']; } break; case 'delete': if ($cart) { $items = explode(',',$cart); $newcart = ''; foreach ($items as $item) { if ($_GET['id'] != $item) { if ($newcart != '') { $newcart .= ','.$item; } else { $newcart = $item; } } } $cart = $newcart; } break; case 'update': if ($cart) { $newcart = ''; foreach ($_POST as $key=>$value) { if (stristr($key,'qty')) { $id = str_replace('qty','',$key); $items = ($newcart != '') ? explode(',',$newcart) : explode(',',$cart); $newcart = ''; foreach ($items as $item) { if ($id != $item) { if ($newcart != '') { $newcart .= ','.$item; } else { $newcart = $item; } } } for ($i=1;$i<=$value;$i++) { if ($newcart != '') { $newcart .= ','.$id; } else { $newcart = $id; } } } } } $cart = $newcart; break; } $_SESSION['cart'] = $cart; |