I am really beginner on PHP and Android and I can't find the problem.
Here is the by return book PHP code.
Firstly it takes two variables Id and id. It selects id from Books database if the id matches it store the Books database variables.
If takenby === Id it should assign true to $success, otherwise it should assign false to $success but every time $success is null.
I don't understand why it is always null.
Thank for your answering...
<?php
$con = mysqli_connect("localHost","name","password","database");
$id = $_POST["id"];
$Id = $_POST["Id"];
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_set_charset($con, 'utf8');
$statement2 = mysqli_prepare($con, "SELECT * FROM Books WHERE id = ?");
mysqli_stmt_bind_param($statement2,"s" , $id);
mysqli_stmt_execute($statement2);
mysqli_stmt_store_result($statement2);
mysqli_stmt_bind_result($statement2, $name, $author, $ıd, $date, $takenby);
$response = array();
$response["success"] = false;
if($takenby===$Id)
{
$statement = mysqli_prepare($con,"UPDATE Books SET takenby = '' , date = '' WHERE id = ?");
mysqli_stmt_bind_param($statement,"s" , $id);
$success = mysqli_stmt_execute($statement);
}
$response = array();
$response["success"]=$success;
$response["id"] = $id;
//json data formatı
echo json_encode($response);
mysqli_close($con);
?>
Here is the console output,
Value null at success of type org.json.JSONObject$1 cannot be converted to boolean.
The problem is in that script is missing the fetch part. After I realized that fetch is missing, and I fetch statement.
Here is some example from PHP documentation about fetch
<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll();
print_r($result);
?> [1]
If someone encounters some kind of problem, ı hope that it would help.
[1] http://php.net/manual/en/pdostatement.fetchall.php
Related
My goal is to update 4 column in my table in a single query.But end up only 1 column is updated,the other 3 is not.
My query is like this
$stmt = $this->conn->prepare("UPDATE users_info SET profile_image_path = ?,user_bio = ? ,gender = ?,date_of_birth = ? WHERE user_id = ?");
$stmt->bind_param("sssii",$profile_image_upload_url,$user_bio,$gender,$date_of_birth,$user_id);
$result = $stmt->execute();
$stmt->close();
return $result;
Here is my code for the query call
//update to database
global $user_id;
$db = new DBhandler();
$update_result = $db->callForQueryFunction($user_id,$user_bio,$date_of_birth,$gender,$profile_image_string);
$response = array();
if($update_result){
$response['error'] = false;
$response['message'] ="sucess";
}else{
$response['error'] = true;
$response['message'] ="fail";
}
After I run in advanced rest client ,with the the following query
user_bio=hihi&gender=f&profile_image_string=somestringhere&date_of_birth=2015-08-16
After run the query,the result is always "success",but in Mysql table only profile_image_path column is updated,the rest 3 column user_bio,date_of_birth and gender all are not updated.
Here is my database structure
I work for hours still haven't figure it out what's wrong with the code or my database structure.
Update:
I tried with bind_param for s with $date_of_birth,but still no luck with it
$stmt->bind_param("ssssi",$profile_image_upload_url,$user_bio,$gender,$date_of_birth,$user_id);
UPDATE
I actually using this example from Androidhive,the sample code is as below
/**
* Updating existing task
* method PUT
* params task, status
* url - /tasks/:id
*/
$app->put('/tasks/:id', 'authenticate', function($task_id) use($app) {
// check for required params
verifyRequiredParams(array('task', 'status'));
global $user_id;
$task = $app->request->put('task');
$status = $app->request->put('status');
But I use the same method as below to grab the value,but after var_dump() all the value is NULL.Here is my code
$app->put('/updateuserdetails','authenticate',function ()use ($app){
$user_bio = $app->request()->put('userbio');
$gender =$app->request()->put('gender');
$date_of_birth = $app->request()->put('dob');
$profile_image_string = $app->request()->put('profilestring');
I try this as well.The value of user_bio,gender,date_of_birth are all still null.
$app->post('/updateuserdetails','authenticate',function ()use ($app){
$user_bio = $app->request()->post('userbio');
$gender =$app->request()->post('gender');
$date_of_birth = $app->request()->post('dob');
$profile_image_string = $app->request()->post('profilestring');
I just cant figure out what is going wrong here
Update
After I test it in Postman by send data with x-www-form-urlencoded it come out with this error,which I cant get any solution
Try the following:
$stmt = $this->conn->prepare("UPDATE users_info SET profile_image_path = :image, user_bio = :bio, gender = :gender, date_of_birth = :dob WHERE user_id = :id");
$stmt->bindParam(":image", $profile_image_upload_url, PDO::PARAM_STR);
$stmt->bindParam(":bio", $user_bio, PDO::PARAM_STR);
$stmt->bindParam(":gender", $gender, PDO::PARAM_STR);
$stmt->bindParam(":dob", $date_of_birth, PDO::PARAM_STR);
$stmt->bindParam(":id", $user_id, PDO::PARAM_INT);
$result = $stmt->execute();
$stmt->close();
return $result;
Hi i am creating an android app which i am currently at a halt because my sql skills are not up to scratch. I am using json.response to run the following php.
Situation: I am checking the table column (users_watched) to see if the user_id exists inside it based on title_text, since its a number i am using ,1,(example) commas around the number so it doesn't get confused with something like 101, and returns that value. If the user_id is not in the row, then add it to the end of the string.
Text Data: user_id = '10,' - watched_title = 'video_title' - temp_user_id = ',10,'
$user_id = $_POST["user_id"];
$watched_title = $_POST["watched_title"];
$temp_user_id = $_POST["temp_user_id"];
$like_input = "'%".$temp_user_id."%'";
$statement = mysqli_prepare($con, "UPDATE videos SET users_watched = CONCAT(users_watched, '?') WHERE users_watched NOT LIKE ? AND title_text = ?");
mysqli_stmt_bind_param($statement, "sss", $user_id, $like_input, $watched_title);
mysqli_stmt_execute($statement);
Result: It is not adding the value to the end of the appropriate string.
Expected Output Add user_id = 10, to the end of the string based on videos_watched
<?php
$user_id = $_POST["user_id"];
$watched_title = $_POST["watched_title"];
$temp_user_id = $_POST["temp_user_id"];
$like_input = "%".$temp_user_id."%";
try {
$con = new PDO('mysql:host=$host;dbname=$dbname','$username', '$pass');
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $con->prepare("UPDATE videos SET users_watched = CONCAT(users_watched, :userid) WHERE users_watched NOT LIKE :like_input AND title_text = :watched_title");
$stmt->bindParam(':userid', $userid);
$stmt->bindParam(':like_input', $like_input);
$stmt->bindParam(':watched_title', $watched_title);
$stmt->execute();
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
I am new when it comes to php, SQL and still learning, I am trying to get the last 4 string value of my column where the value is a telephone numbers: (7258787)
I am trying to display the last 4 string even the search query is full 7 string (8787) base on what i have read SUBSTRING(column_name, -4) will result the last 4 strings from the right.
my codes returns undefined, can you enlighten me with this?
if (isset($_GET['telephone'])) {
$data = "%".$_GET['telephone']."%";
$sql = 'SELECT telephone, SUBSTRING(telephone,-4)FROM employee';
Using this:
$sql = 'SELECT * FROM employee WHERE telephone like ?';
will result the correct value of 7258787 but it will result the whole string(telephone numbers) that i type on a search box
Thank you in advance
This is the whole code:
This is not the answer but the whole script, (credits to Israel Barragan)
In my database I have employee as table and the columns are 'ID', 'NAME', 'TELEPHONE', and 'EMAIL'
<?php
header('Content-Type: application/json');
require_once 'Connectiondb.php';
$conn = dbConnect();
$OK = true; // We use this to verify the status of the update.
if (isset($_GET['telephone'])) {
// Create the query
$data = "%".$_GET['telephone']."%";
$sql = 'SELECT * FROM employee WHERE telephone like ?';
// we have to tell the PDO that we are going to send values to the query
$stmt = $conn->prepare($sql);
// Now we execute the query passing an array toe execute();
$results = $stmt->execute(array($data));
// Extract the values from $result
$rows = $stmt->fetchAll();
$error = $stmt->errorInfo();
//echo $error[2];
}
// If there are no records.
if(empty($rows)) {
echo json_encode( array('error'=>'There were not records','0'=> 'There were not records'));
}
else {
echo json_encode($rows);
}
?>
sorry I am new to stackoverflow,
You can bind the result in your query, and then get the last 4 digits from that to display.
For instance, you can do this
(not you aren't binding your parameters. You need to do something like this)
$stmt->bind_param("s", $data);
and then execute it like this:
$stmt->execute();
In your query instead of using select *, name the specific keys and then you can bind the result like this (assuming all you need is the phone number:
$stmt->bind_result($telephone);
then get the result like so:
$stmt->fetch();
then you can just get a substring off of $telephone like so (in php it is substr())
echo substr($telephone,-4);
(oh yeah and don't forget to close your object with
$stmt->close();
after you are done)
Edit:
Here's your query put together to get the substring
$data = "%".$_GET['telephone']."%";
$stmt = $conn->prepare("SELECT telephone FROM employee WHERE telephone like ?");
$stmt->bind_param("s", $data);
$stmt->execute();
$stmt->bind_result($telephone);
$stmt->fetch();
echo substr($telephone,-4);
$stmt->close();
I have some problem with my if else statement, but I cant figure out what, since it should work :)
What im trying to do is that IF the video_title already exist in my row then do nothing,
but if the video_title does not exist, insert values to the table.
I have the value marvel.mp4 in my video_title column,
But it still keeps on inserting marvel.mp4 as value on new rows...
Any ideas why its not working?
$query = $dbh->query("SELECT video_title FROM video");
$q = $query->fetch(PDO::FETCH_OBJ);
$video_title = "marvel.mp4";
if($video_title ==$q){
// Do Nothing
}else{
$sql = "INSERT INTO video (video_title, video_cat, video_date) VALUES (:video_title, :video_cat, NOW())";
$query = $dbh->prepare($sql);
$query->execute(array(
':video_title' => $video_title,
':video_cat' => $video_cat
));
}
It should be:
if ($video_title == $q->video_title)
When you use PDO::FETCH_OBJ, each column is a property of the object.
You also need to be more specific in the query, otherwise you're just testing whether the video is the first one returned by the query.
$video_title = "marvel.mp4";
$stmt - $dbh->prepare("SELECT video_title FROM video WHERE video_title = :title");
$stmt->execute(array(':title' => $video_title));
$q = $stmt->fetch(PDO::FETCH_OBJ);
This code will solve your problem. I have just tested and run it and is working.
Please rate me if you find this help awesome ....Sectona
<?php
$db = new PDO (
'mysql:host=localhost;dbname=sectona_db;charset=utf8',
'root', // username
'tt56u' // password
);
?>
<?php
require("pdo.php");
$video_t=strip_tags($_POST["video_t"]);
//check if the video title already exist in the database
$result = $db->prepare('SELECT * FROM video where video_title = :video_title');
$result->execute(array(
':video_title' => $video_t
));
$nosofrows = $result->rowCount();
if ($nosofrows == 1)
//if ($nosofrows ==0)
{
echo '<br><b><font color=red><b></b>Video Title Already exist. Do not insert</font></b><br>';
exit();
}else{
// insert data
$statement = $db->prepare('INSERT INTO video(video_title,video_name)
values
(video_title,video_name)')
$statement->execute(array(
':video_title' => $video_t,
':video_name' => 'Commando'
));
}
?>
I keep thinking on that "error" but can't say why it returns false.
I've already done a SELECT for this but that is in an other file..
$result = $db->dbh->prepare("SELECT thumbs FROM skill WHERE id=? LIMIT 1");
$result->bindParam(1, $id);
// $id == 4 here
$result->execute();
$row = $result->fetch(PDO::FETCH_ASSOC);
// $row == false > why ?
$thumbs = $row['thumbs'];
When i'm trying to run this on PhpMyAdmin, it works well.
I execute this code on an AJAX call, and using the same config.php file for the $db conection.
Another question:
$sql_in = $db->dbh->prepare("INSERT INTO `voted_ip` (id, ip) VALUES (:id, :ip)");
// $id == 4
$sql_in->bindParam(":id", $id);
$sql_in->bindParam(":ip", $ip, PDO::PARAM_STR);
$sql_in->execute();
it inserts "0" and my ip. Why 0 ?
Please help
That is becasue of the $id which is a STRING is converted at 0 by MySQL.
$id = intval($id);