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.
Related
I'm facing a weird problem, I'm trying to implement a simple Usercheck with PHP 7.1.
$con = getConnection();
//check connection
if(!$con){
die("Connection to database failed". mysql_connect_error() );
} else echo ("connection to database successfull");
//checking if nickname already exists
$checkUserExistanceSql = "SELECT nickname FROM user WHERE nickname='" + $nickname+ "'";
//sending query to sql database
$doesExist = mysqli_query($con, $checkUserExistanceSql)
or die ("Fehler in der Datenbankabfrage");
if(mysqli_num_rows($doesExist)>=1){
echo "Nickname not available, use another name";
}
But I'm getting this warning
Warning: A non-numeric value encountered in E:\XAMPP\htdocs... Line 29
Line 29 is the $checkUserExistanceSql. Any ideas where the problem is?
String concatenation on PHP uses . (dot) as operator, not + (plus).
You actual code uses +:
$checkUserExistanceSql = "SELECT nickname FROM user WHERE nickname='" + $nickname+ "'";
This is why PHP is telling that $nickname isn't a numeric variable. It cannot sum strings, only concatenate.
Change your operator to . and it will work:
$checkUserExistanceSql = "SELECT nickname FROM user WHERE nickname='" . $nickname . "'";
You can also use this syntax, with the same result but cleaner code:
$checkUserExistanceSql = "SELECT nickname FROM user WHERE nickname='{$nickname}'";
Security Alert
You code is sucessive to SQL injection. You should use prepared statements instead of concatenating your variables into the Query.
Thanks to the help of Yolo and Elias Soares.
The script runs flawless now, I also used prepared statement to counter the risk of sql injection as mentiones by elias.
$con = getConnection();
//check connection
if(!$con){
die("Connection to database failed". mysql_connect_error() );
} else echo ("connection to database successfull");
//prepared statement for sql query
$stmt = $con -> prepare("SELECT nickname FROM user WHERE (nickname=?)");
$stmt -> bind_param("s", $nickname);
$stmt->execute();
//checkking result, if nickname is already used
if($stmt->get_result()){
echo "0";
} else {
//insert user
}
I am using the following code to insert Event Logs and User Info from my Mobile App to a mysql database.
I am finding the " Character gives me issues later on when in use with JSON arrays that I pull from the db. What I would like to do is remove the " character in the php code completely before posting to the db.
Removing the " character by Javascript from the Mobile App is not really an option.
<?php
$servername = "localhost";
$username = "Fred";
$password = "Barney";
$dbname = "BamBam";
// Create connection
$conn = new mysqli ($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// escape variables for security
$event_log = mysqli_real_escape_string($conn, $_POST['event_log']);
$logged_by = mysqli_real_escape_string($conn, $_POST['logged_by']);
$sql = "INSERT INTO time_event (event_log, logged_by)
VALUES ('$event_log', '$logged_by')";
if ($conn->query($sql) === TRUE) {
echo "Data entered successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Use mysqli_prepare and mysqli_stmt_bind_param to execute a parameterised query. I strongly advise this approach.
If you really want to just escape special characters for manual interpolation
into a query string, use mysqli_real_escape_string.
Hand-rolling a solution presents a real risk that you will
miss something important, leaving your program vulnerable
to SQL injection attacks.
I did not try, but this should do
$sql = sprintf("INSERT INTO time_event (event_log, logged_by)
VALUES ('%s' ,'%s'",$event_log,$logged_by);
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));
I've spent today going through tons of similar questions and trying to figure out what is wrong with my code, lots of issues people had with back ticks, quotes, etc but none seem to help or change my cause. My code is no producing any errors, but when I use echo to print out my query results, it seems that the id is not getting a value.
In my delete.php:
<?
ini_set('display_errors',"1");
$username="xxx";
$password="xxx";
$database="xxx";
$conn = new mysqli(localhost, $username, $password, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$id = (int)$_GET['number'];
mysqli_query($conn,"DELETE FROM tourdates WHERE id=".$id."");
$conn->close();
?>
And the delete button in my main.php (the rest of the php is correctly displaying my table with data):
<td><a href='delete.php?number='".$row['id']."'>Delete</a></td>
Can someone help pick out what is causing my rows not to delete when I hit the delete button that I have created, or maybe something that more clearly can help me debug? (I don't want to use checkboxes for this).
EDIT:
I also tried this code (while defining the function as $sql and I'm getting a "Success" message:
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
EDIT 2:
I changed the structure following the advice that I should use POST, thinking I might have caught something I didn't notice before, but still not working.
echo "<td><form method='post' action='delete.php'>
<input type='hidden' name='row_id' value=".$row['id']." />
<input type='submit' name='delete_row' />
</form>";
-
if(isset($_POST['delete_row'])) {
$stmt = $conn->prepare("DELETE FROM tourdates WHERE ID = ?");
$stmt->bind_param('i', $_REQUEST['row_id']);
$stmt->execute();
}
If I do it the above way, nothing happens. Also tried this way, and get a syntax error:
if(isset($_POST['delete_row'])) {
$id = $_POST['row_id'];
$sql = "DELETE FROM tourdates WHERE id=".$id;
mysqli_query($conn,$sql);
}
A potential problem that I can see, is that you are not quoting localhost so php will look for a constant called localhost:
$conn = new mysqli('localhost', $username, $password, $database);
^ ^ here
You are also not checking for errors so that is why you don't see any. The easiest way to fix that, is to have mysqli throw exceptions. Just add this to the top of your script:
mysqli_report(MYSQLI_REPORT_STRICT);
I also don't know if you can mix procedural and object oriented mysqli like that. You should probably stick to the OOP version.
Apart from that you should not use a link (GET request) for your delete actions. What if a web-crawler or a browser extension tries to fetch the links? Instead you should use a POST request (like a form with a button).
Edit: There is another problem which causes you not to get your ID and as you cast it to int, you will always get 0:
<td><a href='delete.php?number='".$row['id']."'>Delete</a></td>
^ Oooops, closing the href attribute value here...
Your id gets placed after the value / outside of the quote of the href value. You can easily verify this if you look at the source of your page.
You need:
<td><a href='delete.php?number=".$row['id']."'>Delete</a></td>
Replace these two parts of code in your php file, first write your host in the quotations
$conn = new mysqli('localhost', $username, $password, $database);
in your where condition you wrote id=".$id."" replace it with id=".$id
write it as:
mysqli_query($conn,"DELETE FROM tourdates WHERE id=".$id);
Edited:
If you want to see error in your query then use the below code:
mysqli_query($conn,"DELETE FROM tourdates WHERE id=".$id) or die(mysqli_error($conn));
why not use try and catch to see your error?
anyways try this
$stmt = $conn->prepare("DELETE FROM tourdates WHERE ID = ?");<br>
$stmt->bind_param('i', $_REQUEST['number']);<br>
$stmt->execute();
could this be the problem ?
$id = (int)$_GET['number'];
May be this would be better... ?
$id = intval($_GET['number']);
Anyway if, echo($query) print an empty id, this is probably because your parameter is not an integer.
I need start using the mysqli extension but I'm finding all kinds of conflicting info depending on how all the info is that I'm trying to use.
For example, my header connects to a 'config.php' file that currently looks like this:
<?php
$hostname_em = "localhost";
$database_em = "test";
$username_em = "user";
$password_em = "pass";
$em = mysql_pconnect($hostname_em, $username_em, $password_em) or trigger_error(mysql_error(),E_USER_ERROR);
?>
But when I go to php.net I see that I should be using this but after updating everything I get no database.
<?php
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $mysqli->host_info . "\n";
$mysqli = new mysqli("127.0.0.1", "user", "password", "database", 3306);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $mysqli->host_info . "\n";
?>
I also went through and added an "i" to the following code in my site and again no luck:
mysql_select_db($database_em, $em);
$query_getReview =
"SELECT
reviews.title,
reviews.cover_art,
reviews.blog_entry,
reviews.rating,
reviews.published,
reviews.updated,
artists.artists_name,
contributors.contributors_name,
contributors.contributors_photo,
contributors.contributors_popup,
categories_name
FROM
reviews
JOIN artists ON artists.id = reviews.artistid
JOIN contributors ON contributors.id = reviews.contributorid
JOIN categories ON categories.id = reviews.categoryid
ORDER BY reviews.updated DESC LIMIT 3";
$getReview = mysql_query($query_getReview, $em) or die(mysql_error());
$row_getReview = mysql_fetch_assoc($getReview);
$totalRows_getReview = mysql_num_rows($getReview);
And here's the only place on my display page that even mentions mysql so far:
<?php } while ($row_getReview = mysql_fetch_assoc($getReview)); ?>
I did see something at oracle that another stackoverflow answer pointed someone to that updates this stuff automagically, but I have so little code at this point it seems like overkill.
Adding an i to any mysql function won't make it a valid mysqli function. Even if such function exists, maybe the parameteres are different. Take a look here http://php.net/manual/en/book.mysqli.php and take some time to check mysqli functions. Maybe try some examples to become familiar with the way things work. I also reccomend you to choose either object oriented code, either procedural. Don't mix them.
I just made the switch to mysqli lately, took me a few hours to wrap my head around it. It works well for me, hope it will help you out a bit.
Here the function to connect to the BD:
function sql_conn(){
$sql_host = "localhost";
$sql_user = "test";
$sql_pass = "pass";
$sql_name = "test";
$sql_conn = new mysqli($sql_host, $sql_user, $sql_pass, $sql_name);
if ($sql_conn->connect_errno) error_log ("Failed to connect to MySQL: (" . $sql_conn->connect_errno . ") " . $sql_conn->connect_error);
return $sql_conn;
}
This will return a Mysqli Object that you can use to make you request afterward. You can put it in your config.php and include it or add it at the top of your file, whatever works the best for you.
Once you have this object, you can use it to make your query against the object like so: (in this case, if an error came up it will be outputted in the error_log. I like having it there, you can echo it instead.
//Use the above function to create the mysqli object.
var $mysqli = sql_conn();
//Create the query string (truncated for the example)
var $query = "SELECT reviews.titl ... ... ted DESC LIMIT 3";
//Launch the query on the mysqli object using the query() method
if(!($results = $mysqli->query($query))){
//It it fails, log the error
error_log(mysqli_error($mysqli));
}else{
//Manipulate your data.
//here it depends on what you retunr, a single value, row or a list of rows.
//Example for a set of rows
while ($record = $results->fetch_object()){
array_push($array, $record);
}
}
//Just to show, this will output the array:
print_r($array);
//Close the connection:
$mysqli->close();
So basically, in mysqli, you create an object and use the method to work your way out.
Hope this helps. Once you figured it out, you will most likely enjoy mysqli more that mysql. I did anyway.
PS: Please note that this was copy/pasted from existing, working code. Might have some typo, and might forgot to change a var somewhere, but it's to give you an idea of how mysqli works. Hope this helps.