Jump to content

Search the Community

Showing results for tags 'MySQL'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • W3Schools
    • General
    • Suggestions
    • Critiques
  • HTML Forums
    • HTML/XHTML
    • CSS
  • Browser Scripting
    • JavaScript
    • VBScript
  • Server Scripting
    • Web Servers
    • Version Control
    • SQL
    • ASP
    • PHP
    • .NET
    • ColdFusion
    • Java/JSP/J2EE
    • CGI
  • XML Forums
    • XML
    • XSLT/XSL-FO
    • Schema
    • Web Services
  • Multimedia
    • Multimedia
    • FLASH

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


AIM


MSN


Website URL


ICQ


Yahoo


Jabber


Skype


Location


Interests


Languages

  1. So my question is: how can I insert variables into my mysql queries in php? This is my code now, I would like to use the $me and the $friend variables to work in the sql query: function newChat($me, $friend) { global $conn; $sql = "SELECT id FROM chats WHERE (person1 = $me AND person2 = $friend) OR (person1 = $friend AND person2 = $me);"; mysqli_query($conn, $sql) or die('Error querying database.'); echo "check <br />"; $result = mysqli_query($conn, $sql); $row = mysqli_fetch_array($result); while ($row = mysqli_fetch_array($result)) { echo $row['id'] . ' - ' . $row['person1'] . ' - ' . $row['person2'] . ' - ' . $row['date'] .'<br />'; } } newChat('John', 'Marie'); Also if I set $sql to "SELECT * FROM chats" it only gives me one row of my two test rowes in my database. (it only gives the second row, and just ignores the first one? --> a screenshot of the database is at the end of this post) Can anyone please help me with this? Thanks already!
  2. In phpmyadmin I did the following query and had it output in php like this: $sql = "UPDATE `table` SET count = count + 1 WHERE unique_nr = 5175781"; this all worked well. though when I tried to implement it in my script I had an error: script: <?php // code to establish dbase connection: var_dump($unique_nr); // $stmt = $conn->prepare('UPDATE table SET count = ? WHERE unique_nr = ? '); $stmt = $conn->prepare('UPDATE table SET count = count + 1 WHERE unique_nr = ? '); $stmt->bind_param("is", $count, $unique_nr); $stmt->execute(); ?> resulting in an error message. I also tried this way of writing for bind_param: $stmt->bind_param("s", $unique_nr); but that didnt update the column, though there wasnt an error message anymore
  3. MySQL queries are not working only inside this block: ... if (isset($_POST['send'])) { } ... The variable itself is set and transferred from the form. What could be the reasons of this and how is better to check?
  4. Dear all, For photo gallery tables (named: gallery_album, gallery_image, gallery_relation), I have seen a recommendation to use InnoDB engine in preference to MyISAM. I thought MyISAM would be the choice for all tables but tables for transactions. Do you agree with the recommendation to using InnoDB for photo gallery tables and why?
  5. j.silver

    Index vs Key

    Dear all, I am trying to dig into the exact difference between key and index in MySQL tables. Some say they are synonymous, others give some differences. I still don't feel confident enough to decide when to use each on a table. I would appreciate if someone well-versed in their difference explain such difference and when to use each. Thanks.
  6. Hi all, I have uploaded an image to a folder/directory and stored its size using the $_FILES['image']['size'] superglobal. While the image source size was reading 153kb, the stored size is 157317. Why there is a difference in size?
  7. Dear all. For an image uploaded to a folder/directory and stored its name, type, and size in a DB table, what could be the merits of also storing its temporary name, noting that such temporary name is deleted by the server upon moving the image to the desired folder/directory?
  8. Hi all, In fetching a result from a table (below code), 1 is also printed after the fetched record (fetched record below). There is no 1 in the table, nor have I accidentally included it in my script. What is it and why does it appear? <?php require 'db/connect.php'; if($result = $db->query("SELECT * FROM user")) { if ($count = $result->num_rows) { $rows = $result->fetch_assoc(); echo '<pre>', print_r($rows), '</pre>'; } } ?> Array ( [id] => 1 [first_name] => Bill [last_name] => John [bio] => I'm a web developer [created] => 2016-11-21 12:50:12 ) 1
  9. Hi all, <?php require 'db/connect.php'; $result = $db->query("SELECT * FROM people"); ?> I obtained a blank page running the above script, which indicates that everything is fine (path and table name are correct). I then removed the * from the query to see if it would report an error, but it did not. I added print_r($result); and run it. Nothing has changed. I included the * and run, it reported the number of rows and columns in the table. Why there has a been a lack of error reporting in this instance, noting that the ini file is configured to report all sorts of errors, even the warnings and notices (and it is reporting all that in other scripts)?
  10. Hi all, In one website, I read the following note: "You should also think about storing files locations on disk. Using MySQL for storing images is thought to be Bad Idea™. Handling SQL table with big data like images can be problematic." Do you agree? If not, why? What is the best practice in storing and displaying on a website a big number of images?
  11. I'm trying to select data from a MySQL database that is hosted on a webserver. I want to be able to retrieve the data from a table within the database and then illustrate it within a HTML table. There's an example on W3Schools that I've been following, but I'm unable to retrieve the data successfully. http://www.w3schools.com/php/php_ajax_database.asp Below is the source code: (HTML) <html> <head> //Javascript code <script> function showUser(str) { if (str == "") { document.getElementById("txtHint").innerHTML = ""; return; } else { if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("txtHint").innerHTML = this.responseText; } }; xmlhttp.open("GET","getuser.php?q="+str,true); xmlhttp.send(); } } </script> </head> <body> <form> <select name="users" onchange="showUser(this.value)"> <option value="">Select a person:</option> <option value="1">Peter Griffin</option> <option value="2">Lois Griffin</option> <option value="3">Joseph Swanson</option> <option value="4">Glenn Quagmire</option> </select> PHP File: (getuser.phd) <!DOCTYPE html> <html> <head> <style> table { width: 100%; border-collapse: collapse; } table, td, th { border: 1px solid black; padding: 5px; } th {text-align: left;} </style> </head> <body> <?php $q = intval($_GET['q']); $con = mysqli_connect('www.example.com','user_Admin','12345-678','my_DB'); if (!$con) { die('Could not connect: ' . mysqli_error($con)); } mysqli_select_db($con,"ajax_demo"); $sql="SELECT * FROM user WHERE id = '".$q."'"; $result = mysqli_query($con,$sql); echo "<table> <tr> <th>Firstname</th> <th>Lastname</th> <th>Age</th> <th>Hometown</th> <th>Job</th> </tr>"; while($row = mysqli_fetch_array($result)) { echo "<tr>"; echo "<td>" . $row['FirstName'] . "</td>"; echo "<td>" . $row['LastName'] . "</td>"; echo "<td>" . $row['Age'] . "</td>"; echo "<td>" . $row['Hometown'] . "</td>"; echo "<td>" . $row['Job'] . "</td>"; echo "</tr>"; } echo "</table>"; mysqli_close($con); ?> </body> </html> *MySQL table is attached I think the issue might exist from mysqli_select_db($con,"ajax_demo"); onwards inside the PHP file. Should I be referring to the table that contains the data inside the database? I have the PHP File hosted on my webserver, so I'm not sure why it won't retrieve that data when a person is selected from the list of options on the HTML page. Any help would be much appreciated.
  12. j.silver

    utf8 VS utf8mb4

    Dear all, I came across the following statement on one website: "Note: Since MySQL 5.5.3 you should use utf8mb4 rather than utf8. They both refer to the UTF-8 encoding, but the older utf8 had a MySQL-specific limitation preventing use of characters numbered above 0xFFFD." 1) Is there any drawbacks in using utf8mb4, or it is recommended for use from now on?
  13. Hi I have been working on building a custom post a result set to a database which thankfully I have now managed with some help, now I am working on the other end of this project the displaying the saved data back to users, From the start of this I have an online tournament hosting group that go to my form and post a list of player names with points earned per tournament. Once the form is submitted it's sent to my form_processing.php where the results are exploded and split into 2 arrays "$player_name, $points" Then on the INSERT I have an INSERT $sql = "INSERT into `bg_points` (`player_name`, `points`) values (?, ?) on duplicate key update points = points + ?"; to of course update current player points if the exist or add new records if not. Then finally saved into my DB table, now I am working on building the page to display these points back to the players so they can track their earned points and standings each month. which is easy enough I just call an MySQL SELECT * FROM statement on the DB table that's done, Now I need to sort these results in lowest to highest order by points so if player1 has 120 points player2 has 50 points player3 has 75 points player4 has 5 points then I need to be displaying these back as player4 player2 player3 player1 I have had a look online for some possible examples to help guide me into this and I either get HTTP 500 or just no effect at all. here is the very basic code I have put together so far which I can and will update and add into my site framework once I have it in order and working... <HTML> <head></head> <body bgcolor="#0000FF"> <?PHP $servername = "localhost"; $username = "***********"; $password = "*******"; $dbname = "***********"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } //output the saved data $sql = "SELECT * FROM `bg_points` "; $result = $conn->query($sql); if ($result->num_rows > 0) { // output data of each row while($row = $result->fetch_assoc()) { echo "id: " . $row["id"]. " $nbsp $nbsp Playerv Name: " . $row["player_name"]. " $nbsp $nbsp Points: " . $row["points"]. "<br>"; } } else { echo "0 results"; } $conn->close(); ?> </body> </html> thanks for any help or ideas in advanced
  14. Hi I am having trouble inserting data into my MySQL database. This is my PHP code ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); static $connection; if(!isset($connection)) { $connection = new mysqli("localhost","username","password"); } if ($connection->connect_error) { die("Connection failed: " . $connection->connect_error); } $stmt = $connection->prepare("INSERT into Product(product_title,product_price,product_availability,productImage_1,productImage_2,productImage_3,productImage_4,product_description,product_shipping,product_pickup) VALUES(?,?,?,?,?,?,?,?,?,?)"); $product_title = $_POST['title']; $product_price = $_POST['price']; $product_availability = $_POST['stock']; $null = NULL; $product_description = $_POST['description']; $product_shipping = $_POST['postage']; $product_pickup = $_POST['pickup']; $stmt->bind_param('sisbbbbsis',$product_title,$product_price,$product_availability,$null,$null,$null,$null,$product_description,$product_shipping,$product_pickup); $stmt->send_long_data(3, file_get_contents($_FILES['img1']['tmp_name'])); $stmt->send_long_data(4, file_get_contents($_FILES['img2']['tmp_name'])); $stmt->send_long_data(5, file_get_contents($_FILES['img3']['tmp_name'])); $stmt->send_long_data(6, file_get_contents($_FILES['img4']['tmp_name'])); $stmt->execute(); $stmt->close(); $connection->close(); echo "Product inserted successfully"; I am also getting these errors. Notice: Undefined index: title in /Applications/MAMP/htdocs/Bourke/insertproduct.php on line 61 Notice: Undefined index: price in /Applications/MAMP/htdocs/Bourke/insertproduct.php on line 62 Notice: Undefined index: stock in /Applications/MAMP/htdocs/Bourke/insertproduct.php on line 63 Notice: Undefined index: description in /Applications/MAMP/htdocs/Bourke/insertproduct.php on line 67 Notice: Undefined index: postage in /Applications/MAMP/htdocs/Bourke/insertproduct.php on line 68 Notice: Undefined index: pickup in /Applications/MAMP/htdocs/Bourke/insertproduct.php on line 69 Fatal error: Call to a member function bind_param() on boolean in /Applications/MAMP/htdocs/Bourke/insertproduct.php on line 71 Thanks in advance.
  15. <?php $host = 'localhost'; $username = 'root'; $password = ''; $datadase = 'registerfinal'; $connect = mysqli_connect($host, $username, $password) or die ('error to connect to datadase'.mysqli_error()); if ($connect) { echo 'mysqli connect succsessfull'; } echo '<br /><br />'; $selectdb = mysqli_select_db($connect, $datadase) or die ('unable to select datadase'.mysqli_error()); if($selectdb) { echo 'database selected succsessfully'; } if(isset($_POST['savedetails'])) { $firstname = $_POST['firstname']; $lastname = $_POST['lastname']; $username = $_POST['username']; $password = $_POST['password']; $repeat_password = $_POST['repeat_password']; $gender = $_POST['gender']; $country = $_POST['country']; if(isset($_POST['food'])) { $food = $_POST['food']; $favfood = ""; foreach($food as $meal ) { $favfood = $meal.","; print_r($favfood); } } if(isset($_POST['imageUpload'])) { $imageUploadname = $_FILES['imageUpload']['name']; $imageUploadsize = $_FILES['imageUpload']['size']; $imageUploadtmp_name = $_FILES['imageUpload']['tmp_name']; $imageUploadtype = $_FILES['imageUpload']['type']; $uploadFolder = "uploadFolder/"; $destinationName = rand(1000, 10000).$imageUploadname; move_uploaded_file($imageUploadtmp_name, $uploadFolder.$destinationName); echo "$imageUploadname"; echo "$imageUploadsize"; echo "$imageUploadtmp_name"; echo "$imageUploadtype"; echo "$destinationName"; } $sqltwo = "INSERT INTO `registerfinaltable` (`id`, `firstname`, `lastname`, `username`, `password`, `repeat_password`, `gender`, `food`, `country`, `imageUploadname`, `imageUploadsize`, `imageUploadtype`) VALUES (NULL, '$firstname', '$lastname', '$username', '$password', '$repeat_password', '$gender', '$favfood', '$country', '$destinationName', '$imageUploadsize', '$imageUploadtype')"; $results = mysqli_query($connect, $sqltwo) ; if($results){ echo "inserted successfully"; } } ?> <html> <head> <title>register</title> </head> <body> <form action = "" method = "post" enctype = "multipart/form-data" > <label>first name : <input type = "text" name = "firstname" /> </label> <br /><br /> <label>last name : <input type = "text" name = "lastname" /> </label><br /><br /> <label>username : <input type = "text" name = "username" /> </label><br /><br /> <label>password : <input type = "password" name = "password" /> </label><br /><br /> <label>repeat password : <input type = "password" name = "repeat_password" /> </label><br /><br /> <label>Male : <input type = "radio" name = "gender" value = "Male" /> </label><br /><br /> <label>Female : <input type = "radio" name = "gender" value = "Female" /> </label><br /><br /> <label>pizza : <input type = "checkbox" name = "food[]" value = "pizza"/> </label><br /><br /> <label>burger : <input type = "checkbox" name = "food[]" value = "burger"/> </label><br /><br /> <label>chips : <input type = "checkbox" name = "food[]" value = "chips"/> </label><br /><br /> <label>sausage : <input type = "checkbox" name = "food[]" value = "sausage"/> </label><br /><br /> <label>sandwich : <input type = "checkbox" name = "food[]" value = "sandwich"/> </label><br /><br /> <label>Image : <input type = "file" name = "imageUpload" /> </label><br /><br /> <select name = "country"> <?php $sql = 'SELECT * FROM `countrie` '; $querry = mysqli_query($connect, $sql); while($country = mysqli_fetch_array($querry)):; ?> <option value = "<?php echo $country['country']; ?>"><?php echo $country['country']; ?></option> <?php endwhile;?> </select> <br /> <input type = "submit" name = "savedetails" /> </form> <table border = "1" bgcolor = "" width = "100%"> <tr><th>id</th><th>Firstname</th><th>Lastname</th><th>Username</th><th>Password</th><th>Password 2</th><th>Gender</th><th>Fav. Food</th> <th>Image</th> <th>Country</th><th>imageUploadname</th><th>imageUploadsize</th><th>imageUploadtype</th></tr> <?php $sqldata = "SELECT * FROM registerfinaltable"; $querysqldata = mysqli_query($connect, $sqldata); while($rows = mysqli_fetch_array($querysqldata) ):; ?> <tr> <td><?php echo $rows['id'];?></td> <td><?php echo $rows['firstname'];?></td> <td><?php echo $rows['lastname'];?></td> <td><?php echo $rows['username'];?></td> <td><?php echo $rows['password'];?></td> <td><?php echo $rows['repeat_password'];?></td> <td><?php echo $rows['lastname'];?></td> <td><?php echo $rows['gender'];?></td> <td><?php echo $rows['food'];?></td> <td><?php echo $rows['country'];?></td> <td><?php echo $rows['imageUploadname'];?></td> <td><?php echo $rows['imageUploadsize'];?></td> <td><?php echo $rows['imageUploadtype'];?></td> <?php endwhile;?> </tr> </table> </body> </html>
  16. My goal is to store javascript code into a database. My first idea was to use htmlspecialchars; store it in mysql in a table column and later retrieve it with htmlspecialchars_decode. All this to prevent injection / hacking. But online I read one or two warnings that it wouldnt work, which I assume is so (I didnt test it, but it seems quite obvious afterwards) . So my question is: is it possible to have a user store javascript in a database and use it in a php script for specific purposes in a secure way?
  17. Hi i am new for the PHP, i had the experienced before to do a login system page but what i want it is HTML and PHP file to separate i dont want PHP with HTML together to 1 file , cause professional people will more likely to use 2 file rather than 1 file easy to maintain and edit how to use the external PHP file coding without re-design whole page cause normally what i tested before was link or turn to other new page and result will come out but the design was totally gone so have any ways and suggestion to do that ... in the end, im sorry i not well in english and my knowledge of PHP still quite new , thanks you so much
  18. HI i trying to create a website of forum textarea editor are necessary too for recommendation which editor are best for textarea such as summernote, wysihtml5 .... and how is work to store the data/value/text with styling effect in mysql database ? Thanks all of you
  19. HI i trying to create a website of forum textarea editor are necessary too for recommendation which editor are best for textarea such as summernote, wysihtml5 .... and how is work to store the data/value/text in mysql database ? Thanks all of you
  20. HI i trying to create a website of forum textarea editor are necessary too for recommendation which editor are best for textarea such as summernote, wysihtml5 .... and how is work to store the data/value/text in mysql database ? Thanks all of you
  21. <?php $serv = "localhost:81"; $user = "root"; $password = ""; try { $con = new PDO("mysql:host=$serv;dbname=test", $user, $password); $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo "Successfully connected."; } catch (PDOException $e) { echo "Connection failed: " . $e->getMessage(); } ?> Here I'm trying to use PDO to connect to my SQL database "test". However, I receive this error each time I connect: SQLSTATE[HY000] [2002] No connection could be made because the target machine actively refused it. Am I connecting with the wrong server, user or password? Because I fail to see here the mistake.
  22. Hi, I'm trying to get a form where you submit information about a home to a database and below the form it displays the homes with the information and a photo. Below the home information and photo I have a button to DELETE RECORD and a button to upload a photo. All of the php and forms are in one file so submitting the home info and deleting record are just have action="samefile.php". This is so that it stays on the same page and doesn't have to jump to another page. I cannot get the upload photo to stay on the same page. The only way I can get the upload photo to work is to send it to another file. This of course takes me to another page which I don't want. I want everything to stay on the same page. The code I have (in a file called "PicTest03.php) is as follows: <!DOCTYPE html> <head> </head> <html> <body> <form action="PicTest03.php" method="POST"><pre> Name <input type="" name="name"> Bedrooms <input type="text" name="bedrooms"> Length <input type="text" name="length"> Width <input type="text" name="width"> Serial Number <input type="text" name="serialno"> <input type="submit" value="ADD RECORD"> </pre> </form> <br><br><br> <?php require_once 'login.php'; $conn = new mysqli($hn, $un, $pw, $db); if ($conn->connect_error) die($conn->connect_error); if (isset($_POST['delete'])&& isset($_POST['serialno'])) { $serialno = get_post($conn, 'serialno'); $query = "DELETE FROM holidayhomes WHERE serialno='$serialno'"; $result = $conn->query($query); if (!$result) echo "DELETE failed: $query<br>" . $conn->error . "<br><br>"; } if (isset ($_POST['name']) && isset ($_POST['bedrooms']) && isset ($_POST['length']) && isset ($_POST['width']) && isset ($_POST['serialno'])) { $name = get_post ($conn, 'name'); $bedrooms = get_post ($conn, 'bedrooms'); $length = get_post ($conn, 'length'); $width = get_post ($conn, 'width'); $serialno = get_post ($conn, 'serialno'); $query = "INSERT INTO holidayhomes (name, bedrooms, length, width, serialno) VALUES ('$name','$bedrooms', '$length', '$width', '$serialno')"; $result = $conn->query($query); if (!$result) echo "INSERT failed: $query<br>" . $conn->error . "<br><br>"; } $query = "SELECT * FROM holidayhomes"; $result = $conn->query($query); if (!$result) die ("Database access failed: " . $conn->error); $rows = $result->num_rows; for ($j = 0 ; $j < $rows ; ++$j) { $result->data_seek($j); $row = $result->fetch_array(MYSQLI_NUM); echo <<<_END <pre> name $row[0] Bedrooms $row[1] Length $row[2] Width $row[3] Serial No $row[10] MainPic $row[4] <img src="uploads/$row[4]" width=200 height=200> </pre> <pre> <form action="PicTest03.php" method="POST"> <input type="hidden" name="delete" value="yes"> <input type="hidden" name="serialno" value="$row[10]"> <input type="submit" value="DELETE RECORD"> </form> </pre> <pre> <form action="mainphoto01.php" method="post" enctype="multipart/form-data"> Select main photo: <input type="hidden" name="serialno" value="$row[10]"> <input type="file" name="fileToUpload" id="fileToUpload"> <input type="submit" value="Upload Image" name="submit"> </form> </pre> <br><br> _END; } $result->close(); $conn->close(); function get_post($conn, $var) { return $conn->real_escape_string($_POST[$var]); } ?> </body> </html> The code for "mainphoto01.php is: <?php require_once 'login.php'; $conn = new mysqli($hn, $un, $pw, $db); if ($conn->connect_error) die($conn->connect_error); $target_dir = "uploads/"; $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $uploadOk = 1; $imageFileType = pathinfo($target_file, PATHINFO_EXTENSION); if(isset($_POST["submit"])) { $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); if($check !== false){ echo "FIle is an image - " . $check["mime"] . "." ; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } } if ($uploadOk == 0){ echo "Sorry, your file was not uploaded."; } else { if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)){ echo "The file " . basename( $_FILES["fileToUpload"]["name"]) . " has been uploaded."; } else { echo "Hello!"; } } $mainpic = basename( $_FILES["fileToUpload"]["name"]); if(isset($_POST["serialno"])) $serialno = $_POST['serialno']; $query = "UPDATE holidayhomes SET mainpic='$mainpic' WHERE serialno='$serialno'"; $result = $conn->query($query); if(!$result) echo "INSERT failed: $query<br>" . $conn->error . "<br><br>"; ?> No matter what I try I cannot get the above code to work if I keep it in the "PicTest03.php" file. Can someone please show what the code should look like so I can get everything to show on the same page? I have had a look as the PHP and AJAX and DATABASE http://www.w3schools.com/php/php_ajax_database.asp which I got the example working but it uses a drop down list. Is there a way to convert the code used for the example on http://www.w3schools.com/php/php_ajax_database.asp and instead of drop down list just have the information from the database shown under the form for submitting the home information?
  23. Hi, I'm trying to follow the JSON example at http://www.w3schools.com/json/json_example.asp I have adjusted the code a little but the code is as follows: jsonTest.html <!DOCTYPE html> <html> <head> <style> h1 { border-bottom: 3px solid #cc9900; color: #996600; font-size: 30px; } table, th , td { border: 1px solid grey; border-collapse: collapse; padding: 5px; } table tr:nth-child(odd) { background-color: #f1f1f1; } table tr:nth-child(even) { background-color: #ffffff; } </style> </head> <body> <h1>Customers</h1> <div id="id01"></div> <script> var xmlhttp = new XMLHttpRequest(); var url = 'jsonTestPHP.php'; xmlhttp.onreadystatechange=function() { if (this.readyState == 4 && this.status == 200) { myFunction(this.responseText); } } xmlhttp.open("GET", url, true); xmlhttp.send(); function myFunction(response) { var arr = JSON.parse(response); var i; var out = "<table>"; for(i = 0; i < arr.length; i++) { out += "<tr><td>" + arr.Name + "</td><td>" + arr.Bedrooms + "</td><td>" + arr.Length + "</td></tr>"; } out += "</table>"; document.getElementById("id01").innerHTML = out; } </script> </body> </html> jsonTest.php <?php header("Access-Control-Allow-Origin: *"); header("Content-Type: application/json; charset=UTF-8"); require_once 'login.php'; $conn = new mysqli($hn, $un, $pw, $db); if ($conn->connect_error) die($conn->connect_error); $result = $conn->query("SELECT name, bedrooms, length FROM holidyhomes"); $outp = "["; while($rs = $result->fetch_array(MYSQLI_ASSOC)) { if ($outp != "[") {$outp .= ",";} $outp .= '{"Name":"' . $rs["name"] . '",'; $outp .= '"Bedrooms":"' . $rs["bedrooms"] . '",'; $outp .= '"Length":"'. $rs["length"] . '"}'; } $outp .="]"; $conn->close(); echo($outp); ?> So I have changed the var url = "http://www.w3schools.com/website/customers_mysql.php"; from the jsonTest.html to var url = 'jsonTestPHP.php'; When I run this I get "Invalid character: var arr = JSON.parse(response);" I just want to be able to grab the data from my database and display it on screen using JSON. Can anyone help me understand why I'm getting this Invalid character error or tell me if I'm going about this the totally wrong way? Thanks
  24. Hi, I'm trying to do a simple website where I can upload some information about homes and add photos to a MySQL database and then display the information. So I have an html form that sends the details of the home to a php file called details.php. The html form is as follows. <!DOCTYPE html> <html> <body> <form action="details.php" method="POST"> <pre> Name <input type="" name="name"> Bedrooms <input type="text" name="bedrooms"> Length <input type="text" name="length"> Width <input type="text" name="width"> Serial Number <input type="text" name="serialno"> <input type="submit" value="ADD RECORD"> </pre> </body> </html> The details.php look like the following: <?php require_once 'login.php'; $conn = new mysqli($hn, $un, $pw, $db); if ($conn->connect_error) die($conn->connect_error); if (isset($_POST['delete'])&& isset($_POST['serialno'])) { $serialno = get_post($conn, 'serialno'); $query = "DELETE FROM holidayhomes WHERE serialno='$serialno'"; $result = $conn->query($query); if (!$result) echo "DELETE failed: $query<br>" . $conn->error . "<br><br>"; } if (isset ($_POST['name']) && isset ($_POST['bedrooms']) && isset ($_POST['length']) && isset ($_POST['width']) && isset ($_POST['serialno'])) { $name = get_post ($conn, 'name'); $bedrooms = get_post ($conn, 'bedrooms'); $length = get_post ($conn, 'length'); $width = get_post ($conn, 'width'); $serialno = get_post ($conn, 'serialno'); $query = "INSERT INTO holidayhomes (name, bedrooms, length, width, serialno) VALUES ('$name','$bedrooms', '$length', '$width', '$serialno')"; $result = $conn->query($query); if (!$result) echo "INSERT failed: $query<br>" . $conn->error . "<br><br>"; } $query = "SELECT * FROM holidayhomes"; $result = $conn->query($query); if (!$result) die ("Database access failed: " . $conn->error); $rows = $result->num_rows; for ($j = 0 ; $j < $rows ; ++$j) { $result->data_seek($j); $row = $result->fetch_array(MYSQLI_NUM); echo <<<_END <pre> Name $row[0] Bedrooms $row[1] Length $row[2] Width $row[3] Serial No $row[10] MainPic <img src="$row[4]" width=auto height=auto><br><br> </pre> <pre> <form action="details.php" method="POST"> <input type="hidden" name="delete" value="yes"> <input type="hidden" name="serialno" value="$row[10]"> <input type="submit" value="DELETE RECORD"> </form> </pre> <pre> <form action="mainphoto.php" method="post" enctype="multipart/form-data"> Select main photo: <input type="file" name="fileToUpload" id="fileToUpload"> <input type="submit" value="Upload Image" name="submit"> </form> </pre> _END; } $result->close(); $conn->close(); function get_post($conn, $var) { return $conn->real_escape_string($_POST[$var]); } ?> ​So the above inserts the information (about a home entered in the html form) into the MySQL database then displays the information and an option to delete the homes information then I have a form to upload a photo for the home. For uploading the photo I have a php file called mainphoto.php which is as follows: <?php require_once 'login.php'; $conn = new mysqli($hn, $un, $pw, $db); if ($conn->connect_error) die($conn->connect_error); $target_dir = "uploads/"; $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $uploadOk = 1; $imageFileType = pathinfo($target_file, PATHINFO_EXTENSION); if(isset($_POST["submit"])) { $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); if($check !== false){ echo "FIle is an image - " . $check["mime"] . "." ; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } } if ($uploadOk == 0){ echo "Sorry, your file was not uploaded."; } else { if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)){ echo "The file " . basename( $_FILES["fileToUpload"]["name"]) . " has been uploaded."; } else { echo " off!"; } } $mainpic = basename( $_FILES["fileToUpload"]["name"]); $query = "INSERT INTO holidayhomes (mainpic) VALUES ('$mainpic')"; $result = $conn->query($query); if(!$result) echo "INSERT failed: $query<br>" . $conn->error . "<br><br>"; ?> How do I get the form to submit and add the name of the photo to the same record(row) as the homes information? So then when it iterates through the record(rows) in the MySQL database I can display the photo to the relevant information about the home?
  25. I have the following peace of code. I cant solve how to fetch all the records in the database. I have to use prepare but if I use place holders for $sql then it doesnt work I tried foreach and while but I dont know how to use it. Can someone please tell what code to use to fetch multiple records from a table? <?php // make connection to database $sql = "SELECT id_nr, name FROM table;"; $id_nr =1; if ($stmt = $conn->prepare($sql)) { $stmt->bind_param('i', $id_nr); $stmt->execute(); $stmt->store_result(); $num_of_rows = $stmt->num_rows; $stmt->bind_result($id_nr, $name); while ($stmt->fetch()) { echo ' id number : ' . $id_nr . '<br>'; echo ' name : ' . $name . '<br>'; } $stmt->free_result(); } $stmt->close(); mysqli_close($conn); } ?>
×
×
  • Create New...