How to fetch data as it is from MySql Database using PHP - php

I am trying to fetch Data from MySQL Database using PHP script from Server. I am able to get Data from Database, but I am not getting the exact string present in Database. In the result obtained the spaces between words get trimmed and result does not match with String present in Database.
For Example:
The value inserted to Database is as shown Below:
SELENIUM INTERVIEW QUESTIONS:
What is Selenium?
Selenium is a set of tools that supports rapid development of test automation scripts for web based applications. Selenium testing tools provides a rich set of testing functions specifically designed to fulfill needs of testing of a web based application.
What are the main components of Selenium testing tools?
Selenium IDE, Selenium RC and Selenium Grid
The result obtained from the Database query shows the data as:
SELENIUM INTERVIEW QUESTIONS:What is Selenium?Selenium is a set of tools that supports rapid development of test automation scripts for web basedapplications. Selenium testing tools provides a rich set of testing functions specifically designed to fulfill needs of testing of a web based application.What are the main components of Selenium testing tools?Selenium IDE, Selenium RC and Selenium Grid
Can any one please let me know what changes should I make in my script to obtain data as it is shown in database from my query. I am using mysql_real_escape_String while inserting and I am using stripslashes while retrieving data from database.
Below is my PHP script:
Insert Script:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "iFocusBlogs";
$obtainedName = urldecode($_POST['enteredName']);
$obtainedUserName = urldecode($_POST['enteredUserName']);
$obtainedsubjectText = urldecode($_POST['subjectText']);
$obtaineddetailsText = urldecode($_POST['detailsText']);
$status = urldecode($_POST['status']);
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$obtainedsubjectText = $conn->real_escape_string($obtainedsubjectText);
$obtaineddetailsText = $conn->real_escape_string($obtaineddetailsText);
$sql = "INSERT INTO AndroidTable (Name, UserName, Subject, Details, Status)
VALUES ('$obtainedName', '$obtainedUserName', '$obtainedsubjectText', '$obtaineddetailsText', '$status')";
mysqli_commit($conn);
if ($conn->query($sql) === TRUE) {
echo "Inserted Post sent to Moderator for Approval. Once approved from Moderator, Post will be displayed";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
fetch Script:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "iFocusBlogs";
$obtainedUserName = 1;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql="SELECT Name, Subject FROM AndroidTable WHERE Status ='" .$obtainedUserName. "'";
$result=mysqli_query($conn,$sql);
while ($row = mysqli_fetch_row($result)) {
foreach($row as $rows){
for($i=0;$i<count($rows);$i++){
echo stripslashes($rows) . " ";
$n=$i;
}
}
echo "<br/>";
}
$conn->close();
?>
Please let me know what mistake am I doing in my script. All suggestions are welcome. If more information required please let me know. Thanks in advance.

You can use nl2br, which will convert new line characters to <br>, so wherever you are echoing, you just need to call nl2br function, see example below:
echo nl2br(stripslashes($rows)) . " ";
EDIT:
To get spaces instead of <br>, you can simply replace new line character \n with space, or anything you would like to replace with, see example below:
echo str_replace("\n", " ", stripslashes($rows))
EDIT 2:
echo stripslashes(str_replace(array('\r\n', '\n'), "<br>", $rows));

Related

How to fix php query in web application search bar and display results

I have a search box in the navigation bar of my web application that appears on every web page. I have a query that is supposed to pull results from my database based on the text the user enters in the search box but at the moment it doesn't show any results.
My web application is essentially a post it board for events so I want a user to be able to search for an event and then have that event displayed in either a table or to take it to the page of the event itself whichever is easier. I am using Netbeans as my IDE and my database is a MariaDB in XAMPP. My web application is just locally hosted for now. I currently have a query that should search the database but I think the output of the query or the result is wrong. I'm not great at PHP but just need to do this as it is in every page of the web application.
The code of the search bar on every page:
<form action="search.php" method="post">
<input type="text" name="search" placeholder="Search for an event..">
<input type="submit" value="Search">
</form>
Then the search.php file looks like this:
<?php
$search = filter_input(INPUT_POST, 'search');
$companyname = filter_input(INPUT_POST, 'companyname');
$eventname = filter_input(INPUT_POST, 'eventname');
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "fyp";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$sql = "SELECT eventname FROM event WHERE eventname LIKE '%$search%'";
if ($conn->query($sql) === TRUE) {
echo "Result Found";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
At the moment, it just comes up saying "Connected successfullyError: SELECT eventname FROM event WHERE eventname LIKE '%Golf%'". I have an event called "SHARE Golf Classic" in the database so that's what I'm testing with currently. I would like to navigate to a page called Event.php and display the results in either a table or else fill labels or textboxes with the details of the event. The event table consists of eventid, eventname, eventtype, charityid, contactdetails, location and date.
Determining errors of objects (Mysqli) can be difficult, that's why you should use try-catch approach instead. Your code could look like this:
<?php
$search = filter_input(INPUT_POST, 'search');
$companyname = filter_input(INPUT_POST, 'companyname');
$eventname = filter_input(INPUT_POST, 'eventname');
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "fyp";
try {
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT eventname FROM event WHERE eventname LIKE '%$search%'";
if (($result = $conn->query($sql)) === true) {
var_dump($result)
}
} catch (mysqli_sql_exception $e) {
var_dump($e)
} finally {
$conn->close();
}
Please bear in mind that using parameters from POST request in the query like this can be dangerous. I would suggest looking into a different MySQL client for PHP (PDO) and use prepared statements instead.
The code example above is also using finally, which was added in PHP 5.5, make sure your version is this or above (currently supported PHP versions are 7.2 and 7.3 - you should be always up to date).

MAX ID count only works every other time

Problem:
I want to get the MAX "SID" from my Database and add one. I handle the input via an Form that i submit through the HTTP Post Method. I get the current MAX "SID" from my database, then i put the value into an HTML input field and add one. For some reason this just works every other time. So the output i get is:
Try = 1
Try = 1
Try = 2
Try = 2
and so on. Would be nice if someone could point me in the right direction.
PHP get MAX(ID):
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "soccer";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
$sql = "SELECT MAX(SID) FROM spieler";
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
$lastID = $row["MAX(SID)"];
}
}
mysqli_close($conn);
PHP insert in database:
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "soccer";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?><br><?php
$sql = "INSERT INTO spieler VALUES ('$sid', '$name', '$verein',
'$position', '$einsaetze', '$startelf', '$tore',
'$torschuesse', '$eigentore', '$vorlagen', '$elfmeter',
'$verwandelt', '$gegentore', '$gelb',
'$rot', '$fouls', '$zweikampf', '$pass', '$note')";
if(mysqli_query($conn, $sql)){
echo "Success";
}else{
echo "Failed" . mysqli_error($conn);
}
mysqli_close($conn);
HTML & PHP Input Field:
<tr>
<td><input id="SID" name="SID" readonly value="<?php echo $lastID += 1;
?>"></td>
</tr>
Screenshot of the page:
The paragraph "Spieler ID:" is where I put the "SID" so that everytime the page loads the next free ID gets automatically loaded into the input field.
I want to get the MAX "SID" from my Database and add one
No. You don't. You really, really don't.
This is the XY Problem.
You can do it by running a system wide lock and a autonomous transaction. It would be a bit safer and a lot more efficient to maintain the last assigned value (or the next) as a state variable in a table rather than polling the assigned values. But this still ignores the fact that you going to great efforts to assign rules to what is a surrogate identifier and hence contains no meaningful data. It also massively limits the capacity and poses significant risks of both accidental and deliberate denial of service.
To further compound the error here, MySQL provides a mechanism to avoid all this pain out of the box using auto-increment ids.
While someone might argue that these are not portable, hence there may be merit in pursuing another solution, that clearly does not apply here, where your code has no other abstraction from the underlying DBMS.

PHP script to Increment value in mysql

I am trying to design a scoreboard for a project for my local youth club and would like to be able to click a button onto a wordpress page that will run a PHP script to update a value by 1 in a sql db table, then i can grab the value and display it else where.
Not too worried about passwords being used in scripts at this will only be used within the local network that nobody else has access to, have looked around and found a few bits of code but im not able to actually get it working, here's what i've got so far.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "sot";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = UPDATE wp_sotstats SET CaptainChest=CaptainChest+1 WHERE id=1
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
The database name is 'sot' the table i want to update is called 'wp_sotstats' and the field within the table is 'CaptainChest' i only need this to really work with just the one entry which the id is '1'
Any thoughts?
$sql = UPDATE wp_sotstats SET CaptainChest=CaptainChest+1 WHERE id=1
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
Is not creating record, it updating it. For me, I will take current value from database as Select, then do ++ to it and do Update query.
$sql = UPDATE wp_sotstats SET CaptainChest=CaptainChest+1 WHERE id=1
Please wrap it in quotes and finish statement with semicolon

How to send text with space from Android to MySQL database

Hello I'm new in Android and I wanna send a text from Android with space (" My Name is Oliver Queen ") to MySQL database.
I use this script in PHP:
<?php
$servername = " ";
$username = " ";
$password = " ";
$dbname = " ";
$id=$_GET['id'];
$project=$_GET["a"];
// Create connection..
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//echo "$project";
$sql= $sql= "UPDATE user SET project = \"$project\" WHERE id= '$id'";
$result = $conn->query($sql);
$conn->close();
?>
In MySQL I found only ("My") The first word before space!
Plzz someone Help Mee !!!!!!
Check the value of $project variable;
My bet is that you send values over a GET request, and not properly encoding them.
If your $project value is indeed "My" like I guess, then look up on you Android part, and look up on how to do url encoding (should be very simple in Java) - look for the equivalent of http://php.net/manual/en/function.urlencode.php - this should resolve your problem.
Also after you get it working, modify the code to deal with SQL Injections, switch to using PDO for DB access, and prepared statements, this would increase the security of your code.
first of all, you should fix your query by using single quotes around the varchar attribute not the numeric, also pay attention to $sql = $sql = you declared it twice:
$sql= "UPDATE user SET project = '$project' WHERE id= $id";
then, you are trying to receive a string by GET method $project=$_GET["a"];, so your URL should be well encoded.

Wordpress - Assign Student Roll Numbers on Form Submission

I am working on an academy website here at www.grmaedu.com
Web Specs: Built on Wordpress with the following plugins, Visual Form Builder Pro & Revolution Slider
So i have managed to do 90% of the work. My query is I want to assign automatic roll numbers to students who are submitting the application form here at www.grmaedu.com/application
Here are the remaining things I want to do:
Automatically assign Roll Number to students "after or on " form submission
Submit the form to the concerned mySql Database, Right now it emails correctly to the designated email address with no issues. All thanks to Visual Form Builder Pro
The date picker field is not working in the application form(I even updated my jQueryUI file)
I hope the provided details are enough for the solution.
I finally figured a way out. Here are the steps which i performed.
I installed a WP Plugin named Contact Form DB. This plugin saves all the form submitted values and stores them in a mySQL database.
I opened up phpmyadmin to see how it was stored and found it in one of the tables. I noticed that each entry had an unique id number. That is what I was trying to do. This plugin made it easier for me.
Then i created a Page template file name rollnumber.php and inserted the following code in
<?php
/* Define Connection properties */
$servername = "localhost";
$username = "grmaedu_wp2";
$password = "******";
$dbname = "grmaedu_wp2";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT entries_id FROM `wp_vfb_pro_entries` ORDER BY entries_id DESC LIMIT 1";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$a = $row["entries_id"];
$a++;
echo "<h3>Your Roll Number assigned is: " . $a . "</h3>";
//echo "id: " . $row["entries_id"] . "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
So now when the page loads it automatically fetches the unique id and adds 1 to the last submitted id and voila a new roll number is generated.
Index key is the best option to set as roll number. because it is unique and then you can get user data directly form this id.
<?php
/* Define Connection properties */
$servername = "localhost";
$username = "grmaedu_wp2";
$password = "******";
$dbname = "grmaedu_wp2";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT entries_id FROM `wp_vfb_pro_entries` ORDER BY entries_id DESC LIMIT 1";
$result = mysqli_query($conn, $sql);
echo "<h3>Your Roll Number assigned is: " . mysqli_insert_id() . "</h3>";
//echo "id: " . mysql_insert_id() . "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>

Categories