I have been getting this T_IF error, but I can't locate any syntax errors. Originally I had the ";" inside of the "" for the sql, but after fixing this the errors continued. I have tried clearing my cache just to be sure that isn't the problem, but no luck.
<?php
require_once 'requires-requires.php';
require 'requires-vars.php';
$mainUser = $row[user];
$coinUser = $mainUser;
$coinExperience = 0;
$coinCoins = 0;
$coinLevels = 0;
$coinUser = mysql_real_escape_string($coinUser);
$coinExperience = mysql_real_escape_string($coinExperience);
$coinCoins = mysql_real_escape_string($coinCoins);
$coinLevels = mysql_real_escape_string($coinLevels);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$servername = "localhost";
$user = "username";
$pass = "password";
$dbname = "databasename";
$conn = new mysqli($servername, $user, $pass, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$usercheck = $conn->query("SELECT user FROM coinchaser WHERE user = '$coinUser'");
$rows_count_value = mysqli_num_rows($usercheck);
if($rows_count_value != 0){
$usernameMatchErr = "You Have Already Joined This Game";
} else {
$sql = "INSERT INTO coinchaser (user, experience, levels, coins) VALUES ('$coinUser', '$coinExperience', '$coinLevels', '$coinCoins')";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
}
}
?>
<div class="wrapper">
<h2>GAMES</h2>
<p> Game: Description </p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Coin Chaser">
</div>
</form>
</div>
</body>
</html>
EDIT: Added full code from the page. The $row[user] comes from one of the included files. This was working prior to me attempting to add the code the below it so I know it is fine. The issue remains with the following portion of the code:
$sql = "INSERT INTO coinchaser (user, experience, levels, coins) VALUES ('$coinUser', '$coinExperience', '$coinLevels', '$coinCoins')";
if ($conn->query($sql) === TRUE) {
As far as debugging the php, I was having issues attempting to do so on this laptop. I have been mainly doing javascript/html/css on this laptop and had forgotten that php needed to be installed on it for the debugging to work properly. I am dusting off my older laptop to see if I can get it to boot up to do a quick php debug on it.
I do plan to put the actual backend operations on their own page. For some reason, I find it simpler to see it working all together on a single page atm as I am still learning sql and trying to become more familiar and comfortable with it rather than bouncing between two pages back and forth trying to find any syntax errors I might have made.
EDIT (SOLVED): I solved the issue. I have no idea why, but for some reason it didn't like the database column named "user" being named "user". My spelling was correct, no syntax issue. I simply went into the database, changed the column name to "username", returned to the file and change "user" to "username" and it worked perfectly.
I solved the issue. I have no idea why, but for some reason it didn't like the database column named "user" being named "user". My spelling was correct, no syntax issue. I simply went into the database, changed the column name to "username", returned to the file and change "user" to "username" and it worked perfectly.
Related
So at the top of the page there is an area for users to create a post with a title and body.
<div class="write_post" id="write_post">
<label for="post_title"><b>Title</b></label>
<input type="text" placeholder="What are you calling this?" name="post_title" required>
<label for="post_body">Body</label>
<textarea name="post_body" id="post_body" rows="5" cols="80" placeholder="Write post here..." required></textarea>
<button action="post.php" class="post_submit" type="submit">Post</button>
</div>
The goal is when they click the post button it will create a post below.
I've tried using javascript to help, but I'm not 100% sure what to do. A push in the right direction would help.
There is no need to use JavaScript in this case – you can use PHP and save the form data in a database.
1. Create an HTML form within a PHP file
First, wrap your input elements in a form (I've only kept the elements that are important in this case):
index.php
<form action="comment.php" method="get">
<input type="text" name="post_title">
<textarea name="post_body"></textarea>
<button type="submit">Post</button>
</form>
2. Create a PHP file to process the submitted form data
As you can see, the form has an action attribute which leads to a file named comment.php. This is just a suitable name I picked, you can name the PHP-file however you like.
In this newly created PHP-file you have to process the submitted form data. Please notice that PHP-files can only run on a server and not locally on your PC like an HTML-file. I would recommend to directly upload and test within a sub-folder on your web server.
A possible folder structure would be:
test-folder
|
+-- index.php
|
+-- comment.php
2. Editing the PHP file and saving data to the database
Open the PHP-File and add the following:
comment.php
2.1 Getting the form data
?php
/*
* Receive the submitted form data and assign it to variables
*/
$comment_title = $_GET["post_title"]; // same as the name attribute in HTML
$comment_body = $_GET["post_body"];
2.2 Creating a new database
We now have the data, but we also want to save it. Data like this is usually saved within a database. Most hosting providers allow you to create one pretty easily.
Your database should have a structure like this:
comments
|
+-- ID (auto increment)
|
+-- comment_title
|
+-- comment_body
2.3 Connecting to the database
We now have to connect to our database to save the data.
/*
* Connect to your database to save the form data
*/
$servername = "localhost"; // get this data from your hosting provider
$username = "username";
$password = "password";
// create a new connection
$conn = new mysqli($servername, $username, $password);
// check if the connection succeeds
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
2.4 Inserting data in to the database
/*
* Insert the form data in to the database
*/
$sql = "INSERT INTO comments (comment_title, comment_body)
VALUES ('".$comment_title."','".$comment_body."',)";
$conn->close();
3. Displaying the saved data
Now we only have to display the saved data on the index.php
We can to this by looping through the rows in our database.
index.php
/*
* Connect to your database and display the saved comments
*/
$servername = "localhost"; // get this data from your hosting provider
$username = "username";
$password = "password";
// create a new connection
$conn = new mysqli($servername, $username, $password);
// check if the connection succeeds
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = mysql_query("SELECT comment_title, comment_body FROM comments");
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
echo $row[0] . $row[1];
}
Im building an app using PHoneGap as the compiler so using HTML5, CSS, JQuery, AJAX etc. Ive manage to get AJAX to GET all the rows from the Database perfectly well, as I have to use .HTML extension on my files I'm struggling to be able to link through to specific DB record. I can do this perfectly in PHP. Im struggling with the HTML part.
Here is my AJAX Loader to get all Rows from DB
var inProcessVideos = false;//Just to make sure that the last ajax call is not in process
setTimeout( function () {
if (inProcessVideos) {
return false;//Another request is active, decline timer call ...
}
inProcessVideos = true;//make it burn ;)
jQuery.ajax({
url: 'https://MY-URL.COM/videos-mysql.php', //Define your script url here ...
data: '', //Pass some data if you need to
method: 'POST', //Makes sense only if you passing data
success: function(answer) {
jQuery('#videos-modules').html(answer);//update your div with new content, yey ....
inProcessVideos = false;//Queue is free, guys ;)
},
error: function() {
//unknown error occorupted
inProcessVideos = false;//Queue is free, guys ;)
}
});
}, 500 );
And here is the contents of the PHP File that renders all the Results from the Database. This part displays the content perfectly.
<?php
include ("../config/mysqli_connect.php");
$sql = ("SELECT * FROM videos");
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "
<a href='" . $row["id"]. "'>
<div class='video-module'>
<div class='video-thumb'><img src='https://MY-URL.COM/thumbs/" . $row["video_thumb"]. "'></div>
<div class='video-thumb-details'>
<div class='video-thumb-title'> " . $row["id"]. " - " . $row["video_title"]. "</div>
" . $row["publisher_name"]. "
</div>
</div></a>
";
}
} else {
echo "0 results";
}
?>
After the ECHO statement I would normally put something like video-Profile.php?id=$id and it would go to that page and pull in that record from the Database.
However now that I have to do it only in HTML, and im assuming AJAX, how to I achieve this.
Here is the PHP and the MYSQL Query to GET the specific record from the Database. Its currently in MYSQL, I will convert it to MYSQLi once I've got it working and got my head around it.
<?php
// Use the URL 'id' variable to set who we want to query info about
$id = ereg_replace("[^0-9]", "", $_GET['id']); // filter everything but numbers for security
if ($id == "") {
echo "Missing Data to Run";
exit();
}
//Connect to the database through our include
include_once "../config/connect_to_mysql.php";
// Query member data from the database and ready it for display
$sql = mysql_query("SELECT * FROM videos WHERE id='$id' LIMIT 1");
$count = mysql_num_rows($sql);
if ($count > 1) {
echo "There is no user with that id here.";
exit();
}
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
$video_title = $row["video_title"];
$video_thumb = $row["video_thumb"];
$publisher_name = $row["publisher_name"];
$video_directory = $row["video_directory"];
$video_path = $row["video_path"];
$upload_date = $row["upload_date"];
$video_views = $row["video_views"];
}
?>
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
<?php echo ("$id");?> - <?php echo ("$video_thumb");?>
</body>
</html>
I know this works if I'm running PHP files, and my server is set to PHPv5.3., but before I make it live, it will be sorted to MYSQLi and run on PHP7???
Im looking for inspiration to get this to function via HTML only files.
thanks for your help everyone.
This is a pretty brutalistic way of doing this - typically you'd return JSON or similar from the PHP and then process this into the HTML elements within your JS. But for this case you can do this:
//within call
success: function(answer) {
var contents = jQuery(answer); // You have now converted the HTML into a jquery model
contents.filter(function(element){
return $(element).attr('id') === id
}) // This allows you to search your child elements and pick them based on criteria
jQuery('#videos-modules').html(contents); // now assign the remaining elements into your html as before
},
I have Tried this but i cant seem to find out how to Run a Console Log as it is Run on iOS iPad at the moment. Can not get it to render in the Browser.
var inProcessVideos = false;//Just to make sure that the last ajax call is not in process
setTimeout( function () {
if (inProcessVideos) {
return false;//Another request is active, decline timer call
}
inProcessVideos = true;//make it burn ;)
jQuery.ajax({
url: 'https://MYURL.COM/appFiles/tablet/video-profile.php', //Define your script url here ...
data: '', //Pass some data if you need to
method: 'GET', //Makes sense only if you passing data
success: function(answer) {
var contents = jQuery(answer); // You have now converted the HTML into a jquery model
contents.filter(function(element){
return $(element).attr('id') === id;
});
jQuery('#videoProfile').html(answer);//update your div with new content, yey ....
inProcessVideos = false;//Queue is free, guys ;)
},
});
}, 500 );
Struggling with this, i've looked at all the JQuery, AJAX MySQL web sites i can find including W3Schools, Jquery.com and many others. Just can not get it to pass the ID to the PHP file to get the Record from the DB via AJAX.
My Links in the first JQuery AJAX Call are:
<a href='video-Profile.html' data='".$row["id"]."' value='".$row["id"]." '>Some HTML STUFF/Images/Text etc</a>
I can get the ID and the First AJAX Call to show ALL the rows in the DB Table. Now just need to show Record by ID. This is what i cant get my head around. And it must be in .HTML Page as its an App compiled via PhoneGap. I know im repeating my self, Just not to sure if im making my point clear. Thanks for the help in advance.
I am trying to connect to my own self created second database using wordpress.
What i am trying to achieve is to extract data from my own database(not wordpress database) on my static wordpress front page.
I use php_everywhere plug in in order for me to write php code in blog post and pages.
I use the following code:
<?php
$servername = "localhost";
$username = "thomas";
$password = "password";
$dbname = "thomas";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * from number";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
However i got an error unexpected '"localhost"' (T_CONSTANT_ENCAPSED_STRING).
Not sure why.
See https://stackoverflow.com/search?q=T_CONSTANT_ENCAPSED_STRING
1) When using that plugin, be sure you've used straight quotes and backspace around the php to remove invisible control characters. And be sure the plugin doesn't have limitations on what it can do and ignores paragraph returns in the editor.
2) You're much better off using a page template in your theme and running PHP in a .php file and not in the post/page editor with a plugin. See Page Templates | Theme Developer Handbook | WordPress Developer Resources. Make a page template, add the calls to header, etc., and then work with your PHP in the file itself. Select the page template in the page editor of the page you're publishing in WordPress.
You can create new object for new database connection and use that object to do any operation for external database
$mydb = new wpdb('thomas','password','thomas','localhost');
$rows = $mydb->get_results("select Name from my_table");
You must have to use $mydb in place of $wpdb
Wordpres provide a way to connect the other db.
$mydb = new wpdb('thomas','password','thomas','localhost');
$rows = $mydb->get_results("select Name from number");
foreach ($rows as $row) :
echo "id: " . $row->id. " - Name: " . $row->firstname. " " . $row->lastname. "<br>";
endforeach;
I have a site with user profiles. I've delete a slew of profiles within phpmyadmin, but those profiles that I've deleted still have their picture files in a folder on the website.
I'm looking for a script that I could run that would select/delete all the pictures in the folder that are not associated with any existing profile in the database.
A typical image name is like this: 0ae71e1bc25cae7e243464adb.jpg
I'm sure there's a way to do this, but I'm not a major expert at using mysql operations for something of this nature.
So in an attempt to be more clear:
I have let's say 100 existing users with their info in the database, including their profile picture name.
Their profile picture is in a folder on the server called images
In that same folder are images of users that do not exist
I'd like to run a script that will check to see if that image is referenced in the "users" table by any user, and if not, delete it.
Your help us appreciated.
I think this script should do the trick.
// Query the images paths as array using mysqli
$db = new mysqli("localhost", "user", "pass", "foo_db");
$result = $db->query("SELECT image_path FROM users");
$images_db = $result->fetch_all(MYSQLI_ASSOC);
// Use glob to retrieve all the existing img in dir
$directory = "/home/user/public_html/images/";
$images_dir = glob($directory . "*.*");
// if image_dir is not in images_db delete it using unlink fn
foreach($images_dir as $image_dir) {
if (!in_array($image_dir, $images_db)) {
unlink($directory . $image_dir);
}
}
You have to tweak the script for your need.
Be carefull with unlink ! First test the script in local !
Lighter on memory solution:
$files = scandir(DIR_TO_IMAGES_FOLDER);
$db_conn = create_db_connection(); //assume this creates the connection to your db and return false if it cant;
if (!$db_conn) exit(); //no connection
foreach ($files as $file){
if (is_file($file)){
$query = "SELECT COUNT(*)
FROM TABLE_NAME
WHERE image_name=:image_name";
$result = $db_conn->prepare($query);
$result->bindParam(":image_name", $file);
$in_use = true; //assume it is in use just incase sql execute fails;
try{
$result->execute();
$in_use = $result->fetchColumn();
}catch (Exception $e){
}
if (!$in_use) unlink(DIR_TO_IMAGES_FOLDER . '/' . $file);
}
}
But I would just create a new TABLE image_delete_pending and a trigger BEFORE DELETE on your 'users' table. The trigger would insert the image_name to the image_delete_pending TABLE. Then the script will for sure know that every image in the image_delete_pending needs to be deleted.
The script would then be:
$db_conn = create_db_connection(); //assume this creates the connection to your db and return false if it cant;
if (!$db_conn) exit(); //end script; no connection
$query = "SELECT image_name
FROM image_delete_pending;";
try{
$result = $db_conn->prepare($query);
$result->execute();
while ($row = $result->fetch()){
if(unlink(DIR_TO_IMAGES_FOLDER . '/' . $row['image_name'])){
$db_conn->query("DELETE FROM image_delete_pending WHERE image_name='". $row['image_name'] ."';";
}
}
}catch (Exception $e){
}
I would like to create a simple text web page that keeps the content. I want to keep the content saved on the server by what ever means (php or sql is fine).
sessionStorage and localStorage isn't what i'm looking for. Those keep the data on the users computer and doesn't allow other computers to see the same thing.
Thanks
So im kind of confused by your question I assume you mean pull string from mysql and display it on the webpage so here is an example.
<?php
//Connect
$user = 'example';
$password = 'example';
$host = 'example';
$link = mysql_connect($host, $user, $password);
mysql_select_db('example_db');
$handle = mysql_query('SELECT * FROM Example_db');
$row = mysql_fetch_row($handle);
$text = $row[0]; // Retrieve text in database
//Variable name above can be what ever you want it to be.
?>
//Example html
<h1><?php echo $text;></h1>
pard me if i'm wrong if so just tell me and I can see if I can further help you.