php passing data with javascript - javascript

forgive me if this is a stupid question or has been asked a million times but I am having trouble using PHP keep in mind I am new to this language so if you guys could break it down simply that would be great.
so I have a file called createchatroom.php it takes user input and creates an SQL table with a column of usernames the main code is here:
$file = ("CREATE TABLE `" . $userstablename . "` (ID int NOT NULL AUTO_INCREMENT, username varchar(255) NOT NULL, PRIMARY KEY (ID))");
and
$sql = "INSERT INTO " . $userstablename . " (username) VALUES ('". $users ."')";
I then have another file called im.php that deals with data from 2 more files get-messages.php and update-messages.php
the im.php is basically all js so I don't really know what is happening there but this could be helpful:
xmlhttp.open("GET","update-messages.php?username=" + username + "&message=" + message,true);
xmlhttp.send();
then the update-messages.php file is:
<?php
$db = new mysqli(connection info here);
if ($db->connect_error) {
die("Sorry, there was a problem connecting to our database.");
}
$username = stripslashes(htmlspecialchars($_GET['username']));
$message = stripslashes(htmlspecialchars($_GET['message']));
if ($message == "" || $username == "") {
die();
}
$result = $db->prepare("INSERT INTO messages VALUES('',?,?)");
$result->bind_param("ss", $username, $message);
$result->execute();
i need to set the "messages" table to "usertablename" from the createchatroom.php document and have no idea how to do that. thanks for your help.

Related

Having issues interpreting json inside php and passing it to mysql

I am new to php and I am not sure how to debug this.
I am trying to pass json to a php page and then send that data to mySQL.
I think it is having issues interpreting the data inside the php file or getting the information to the php page. When I open the php file it gives signs that it is properly accessing the database.
Here is my javascript code:
var request = new XMLHttpRequest();
request.open('POST', 'http://website/saveF.php', true);
request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
request.send(bInfo);
This is taking information in and passing it to a php file to then be added to a mySQL database.
Here is my php code:
This is decoding the jSon and then itterating over each entry inside the array. It then asks the question if it has a website listed or not and stores it into the appropriate table.
//as long as the connection is good then we keep it live.
include_once "head.php";
if ($conn->connect_error) {
die("connection failed: " . $conn->connect_error);
}
//gettting the information from the front end (index.html)
$inputJSON = file_get_contents('php://input');
//decode all the previously encoded information
$postThings = json_decode($inputJSON, TRUE);
$input = filter_var($postThings, FILTER_SANITIZE_STRING);
//create a variable the is the total length of our array
$totalNum = count($input);
//arrays start at 0
$i = 0;
//you can see where this is going. We have a while loop that will continue as long as i is less than totalnum. Ask me why i didn't use a for loop.... I don't have an answer.
while($i < $totalNum){
$var0 = $input[$i][0];
$var1 = $input[$i][1];
$var2 = $input[$i][2];
$var3 = $input[$i][3];
$var4 = $input[$i][4];
$var5 = $input[$i][5];
$var6 = $input[$i][6];
if($var1 == "Not Listed") {
$sql = "INSERT INTO missing(cName, website, rating, phone, id, address, placeType) VALUES ('$var0', '$var1', '$var2', '$var3', '$var4', '$var5', '$var6')";
}else{
//here we set the information into the database.
$sql = "INSERT INTO companies(cName, website, rating, phone, id, address, placeType) VALUES ('$var0', '$var1', '$var2', '$var3', '$var4', '$var5', '$var6')";
}
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$i++;
}
First, note that this line:
$input = filter_var($postThings, FILTER_SANITIZE_STRING);
Will return FALSE if sanitization fails on any of the array elements. In your code, you should be testing if($input) immediately after the sanitization.
Furthermore, you will want to sanitize your inputs further to avoid SQL injection and XSS attacks. (e.g. remove SQL escape characters and other injectable characters).
http://php.net/manual/en/mysqli.real-escape-string.php
Last, it is recommended that you use bound parameters or fully sanitized inputs to avoid a SQL injection attack.

add more information to database without making a new database

I would like to know how users can add multiple images and new data. For example on the site that I'm doing, you can make a design and when you finish you upload it to the database along with your email address title of the design, keywords ect.
I would like to know how its possible to let the user create more designs and named them all in the same database just retrieve them with an email address. I would like to make a limit of 14 designs per email address. But with the database and code that I have now, it only lets one design it just updates every time a new design is created.
Can someone show me the way on how to do this? If you need more information please ask, thank you.
Here is my code:
$query='UPDATE shirt_table SET images="'.$_FILES['file4']['name'].'", images1="'.$_FILES['file1']['name'].'", images2="'.$_FILES['file2']['name'].'", images3="'.$_FILES['file3']['name'].'"
WHERE email= "'.$_SESSION['email'].'"';
if ($mysqli->query($query) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$mysqli->close();
I can see that the uploaded files have different names, you'll have to list the expected file names internally as an array and loop through it that way.
Another thing you need to take care of is when the user has like 13 designs uploaded already and wants to add 4 more designs. You need to decide if you will reject all or add only one. Here is an example I believe you can modify to your taste.
/*
CREATE TABLE `shirt_table` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`email_address` varchar(50) DEFAULT NULL,
`image_path` varchar(100) DEFAULT NULL,
`date_created` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
)
*/
<?php
include("lib/dbcnx.inc.php");
$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME);
$begin = 1;
$end = 5;
$max_uploads = 14;
$sel_query = "select count(*) from shirt_table where email = '".$_SESSION['email']."'";
$result = $mysqli->query($sel_query);
echo $sel_query."<br/>";
$numrows = $result->num_rows;
$counter = 0;
if ($numrows > 0) {
$row = $result->fetch_row();
$counter = $row[0];
}
if ($counter < $max_uploads) {
$saved_dir = "designs/";
$design_files = array($_FILES['file4']['name'], $_FILES['file3']['name'], $_FILES['file2']['name'], $_FILES['file1']['name']);
$query = "INSERT INTO shirt_table (email, image_path, date_created) values ";
for ($i=$begin; $i<=$end; $i++) {
$query = $query ."('".$email."', '".$saved_dir.$design_files[$i-$begin]."', now())";
if ($i < $end)
$query = $query.", ";
}
echo $query."<br/>";
if ($mysqli->query($query) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$mysqli->close();
} else {
echo "You have exceeded ...";
$mysqli->close();
}
?>

Having Issue on Getting Second Session Variable in JavaScript

I have a PHP file getting data from my SQL database and I am trying to set and get two session variables like $_SESSION['fname'] and $_SESSION['userID'] by $theFName and $theId.
$email = $_POST['email'];
$pass = $_POST['pass'];
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_DATABASE);
$sql = "SELECT id, email, fname, lname, type FROM users WHERE `email`=? AND `pass`=?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('ss', $email,$pass);
$stmt->execute();
$stmt->bind_result($theId,$theEmail,$theFName,$theLname,$theType);
if ($stmt->fetch()) {
echo 'true';
$_SESSION['LOGIN_STATUS'] = true;
$_SESSION['fname'] = $theFName;
$_SESSION['userID'] = $theId;
} else {
echo 'false';
}
in JavaScript file I have
<script>
var tok = "var UID = "<?php echo $_SESSION['userID']; ?>";
console.log("The Id is " + UID)
</script>
but I am getting empty string!
can you please let me know what I am doing wrong?
I'm not quite sure I understand what you are trying to do in the JS file, but it is not valid JS in any case - the quotes don't match and it seems like you are trying to do an assignment inside a string.
I think what you are looking for is something more along the lines of this:
<script>
var UID = "<?php echo $_SESSION['userID']; ?>";
console.log("The Id is " + UID)
</script>
However, please note that dynamically generating JS files using PHP is likely not the best way to go about this. Check out this SO answer on the various methods you can use to pass variables from PHP to JS, along with their various pros and cons.

Passing data from ajax to php to mysql weird problems

I asked a similar question earlier, but think I got the wrong point across and learned more about security than fixing the problem I'm having. I am having trouble with my ajax request to post data into a php script and then submit it to a database.
Just to make it clear, the site is local and I will have nobody creating an account besides me and I will be the only one accessing it. I will make it secure once I get this step finished.
Current error I am getting: none, but no data after the success in alert("success" + data)
I have googled/worked for 10+ hours just on this... Any help would be greatly appreciated as I am just learning.
Here is my Javascript:
var firstname = String($("#firstname").val());
var lastname = String($("#lastname").val());
var username = String($("#username").val());
var email = String($("#email").val());
var password = String($("#password").val());
Here is the AJAX:
$.ajax({
type: 'POST',
url: 'create_account.php',
data: {firstname_php: firstname,
lastname_php: lastname,
username_php: username,
email_php: email,
password_php: password},
success: function(data) {
alert("success" + data);
}
});
create_account.php:
$firstname = $_POST['firstname_php'];
$lastname = $_POST['lastname_php'];
$username = $_POST['username_php'];
$email = $_POST['email_php'];
$password = $_POST['password_php'];
echo "$firstname";
// Create connection
$connection = mysqli_connect("localhost","root","root","MyDatabase");
// Check connection
if (mysql_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "INSERT INTO users (user_id, user_firstname, user_lastname, user_username, user_email, user_password) VALUES (0, '$firstname', '$lastname', '$username', '$email', '$password)'";
$result = mysqli_query($connection,$sql);
mysqli_close($connection);
You have a single quote in the wrong place in your query:
VALUES (0, '$firstname', '$lastname', '$username', '$email', '$password)'";
^^^
try this:
VALUES (0, '$firstname', '$lastname', '$username', '$email', '$password')";
Everything looks fine in the javascript and ajax (at least as well as I can tell without seeing the html source as well.
However you have at least one php error; mysql_connect_errno doesn't exist and wouldn't be called in relation to the mysqli connector.
so try this instead:
$firstname = $_POST['firstname_php'];
$lastname = $_POST['lastname_php'];
$username = $_POST['username_php'];
$email = $_POST['email_php'];
$password = $_POST['password_php'];
echo "$firstname";
// Create connection
$connection = mysqli_connect("localhost","root","root","MyDatabase");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "INSERT INTO users (user_id, user_firstname, user_lastname, user_username, user_email, user_password) VALUES (0, '$firstname', '$lastname', '$username', '$email', '$password')";
$result = mysqli_query($connection,$sql);
mysqli_close($connection);
I haven't used the mysqli connector but other than that it looks fine to me. If it still doesn't work I suggest enabling full php debug info - for example adding this to the top of the php file:
ini_set("display_errors", "1");
error_reporting(E_ALL);
EDIT: as hanlet stated you also have a single quote/apos in the wrong spot. (fixed in my example code)

Two questions about possible mysql and php functionalities (maybe javascript?), and where I should look to learn more

First, is it possible for when I insert a record onto my mysql table, a page is automatically generated using the new record in some way. EXAMPLE: My column "image" is on autoincrement, so my image names are always numbers. Furthermore, is it possible for when I insert a record, I automatically generate a page with my image name. So basically, I submit record 367, the image name is 367, and my site will automatically generate mysite.com/367? I want to go in more details but you get the point. Is it possible? If not, what's the closest thing possible?
Also, is there someway to automatically update my page periodically. Such as I set it so at 5pm, it'll automatically insert a code. 5:30pm, it'll insert a different code, which I preprogrammed to do. This is useful, for say I'm on vacation but I still want to update my site regularly.
Can you guys point me to any specific tutorial/terminology/methods/programs/codes/anything? All help would be appreciated!
EDIT: Code I have so far (just want to show to Nick)
<html>
<head>
<title>tgh</title>
</head>
<body>
<?php
$objConnect = mysql_connect("localhost","root","") or die(mysql_error());
$objDB = mysql_select_db("thegoodhumor");
$strSQL = "SELECT * FROM gallery";
if (!isset($_GET['Page'])) $_GET['Page']='0';
$objQuery = mysql_query($strSQL);
$Num_Rows = mysql_num_rows($objQuery);
$Per_Page = 16; // Per Page
$Page = $_GET["Page"];
if(!$_GET["Page"])
{
$Page=1;
}
$Prev_Page = $Page-1;
$Next_Page = $Page+1;
$Page_Start = (($Per_Page*$Page)-$Per_Page);
if($Num_Rows<=$Per_Page)
{
$Num_Pages =1;
}
else if(($Num_Rows % $Per_Page)==0)
{
$Num_Pages =($Num_Rows/$Per_Page) ;
}
else
{
$Num_Pages =($Num_Rows/$Per_Page)+1;
$Num_Pages = (int)$Num_Pages;
}
$strSQL .=" order by GalleryID ASC LIMIT $Page_Start , $Per_Page";
$objQuery = mysql_query($strSQL);
$cell = 0;
echo '<table border="1" cellpadding="2" cellspacing="1"><tr>';
while($objResult = mysql_fetch_array($objQuery))
{
if($cell % 4 == 0) {
echo '</tr><tr>';
}
if($cell == 2) {
echo '<td>RESERVED</td>';
} elseif ($cell == 3) {
echo '<td>The other cell</td>';
} else {
echo '<td><img src="https://s3.amazonaws.com/imagetitle/' . $objResult["Picture"] . '" />' .
$objResult["GalleryName"] . '</td>'; }
$cell++;
}
echo '</tr></table>';
?>
<br>
view more:
<?php
if($Prev_Page)
{
echo " <a href='$_SERVER[SCRIPT_NAME]?Page=$Prev_Page'>prev</a> ";
}
{
echo "|";
}
if($Page!=$Num_Pages)
{
echo " <a href ='$_SERVER[SCRIPT_NAME]?Page=$Next_Page'>next</a> ";
}
?>
</body>
</html>
<?php
mysql_close($objConnect);
?>
It sounds like you want a dynamic web page. To make a dymaic webpage I'd suggest using PHP which would interact with the mysql server.
For example, a user would visit 'mysite.com/info.php?image=367' and the php script would get the information 'image=367'. Your PHP script could do a select query against the mysql database 'SELECT paragraph FROM table WHERE image_id = 367' and then write that data out to the user's web browser.
As far as the user is concerned they just visited 'mysite.com/info.php?image=367', but in the background, PHP dynamically created the webpage content after it got that request.
More basic info about dynamic webpages: http://way.clicktracks.com/help/en/pr650/index.html?dynamicwebsiteshowtheywork.htm
Simple Intro to PHP:
http://www.tizag.com/phpT/
http://www.w3schools.com/php/php_intro.asp
Here is a head start I wrote for you, feel free to use it.
<?php
if (!isset($_GET['imageNumber']))
die("You must specify an image number");
$image_requested = mysql_real_escape_string($_GET['imageNumber']); //sanitizes input
$dbhost = 'localhost'; //TODO: Set this to the ip address of your mysql server if it is not on the same machine
$dbuser = 'root'; //TODO: Set the username you use to access your mysql db here
$dbpass = 'password'; //TODO: Set the password you use to access your mysql db here
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
$dbname = 'database_name_here'; //TODO: Set the database name here
mysql_select_db($dbname);
$query = "SELECT paragraph FROM table_name WHERE image_id = " . $image_requested; //TODO: Set table_name, column to get, and image_id to the correct column name
$result = mysql_query($query);
$row = mysql_fetch_array($result) or die(mysql_error());
echo "Here is the paragraph of text" . $row['paragraph']; //TODO: Set paragraph to the same column you retrieved 3 lines above.
mysql_close($conn);
?>
As for the second part of your question, it can also be done with PHP
<?php
$specifictime = strtotime("tuesday 3pm");
if (time("now") > $specifictime)
{
echo " its after 3pm on tuesday";
}
else {
echo " not 3pm on tuesday yet";
}
?>

Categories