Php save variable (globally?) from local - php

I should really know this by now, but I just can't figure it out anyway. Really weird because I thought I knew it but I just can't get it to work anyway. Well I have this code:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if(isset($_POST['item_id'])){
$item_number = $_POST['item_id'];
require('../includes/db_connect.php');
/* Register a prepared statement */
if ($stmt = $mysqli->prepare('SELECT rotation FROM house_room1 WHERE ref_id = ?')) {
/* Bind parametres */
$stmt->bind_param('i', $item_number);
/* Execute the query */
$stmt->execute();
$stmt->bind_result($rotation);
while ($stmt->fetch()) { }
/* Close statement */
$stmt->close();
} else {
/* Something went wrong */
echo 'Something went terribly wrong' . $mysqli->error;
}
/* Register a prepared statement */
if ($stmt = $mysqli->prepare('UPDATE house_room1 SET rotation = ? WHERE ref_id = ?')) {
/* Bind parametres */
$stmt->bind_param('ii', $i, $item_number);
$i = ($rotation + 1) % 5);
/* Execute the query */
$stmt->execute();
/* Close statement */
$stmt->close();
} else {
/* Something went wrong */
echo 'Something went terribly wrong' . $mysqli->error;
}
}
}
As you can see, I have this variable rotation which I get out from the database in the first SELECT statement. I need this value in the next query, UPDATE but the rotation variable is local I guess? So I can't reach it in the next query, how would I do this most effeciently? Thanks in advance.

You can declare $rotation as $rotation=null; after require statement. This way it will be available on the second query.

Related

How can I make a JSON from a MySQL prepared statement in PHP?

I have this code in PHP where I'm trying to make a JSON based on the result of a prepared statement. The problem is that it is returning a completely white page, nothing appears.
$con = mysqli_connect(HOST,USER,PASS,DB);
$batch_sql = "select * from batchrecord";
$batch_res = mysqli_query($con,$batch_sql);
$row = mysqli_fetch_array($batch_res);
$batch_num = $row[0];
$start = $batch_num * 100;
$end = $start + 99;
if ($stmt = mysqli_prepare($con, "select tweetid, body from tweet where id >=
? and id <= ?")) {
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "ii", $start, $end);
/* execute query */
mysqli_stmt_execute($stmt);
/* bind result variables */
mysqli_stmt_bind_result($stmt, $tweetid, $body);
$result = array();
/* fetch value */
while(mysqli_stmt_fetch($stmt)){
array_push($result,
array('Id'=>$tweetid,
'Body'=>$body,
));
}
/* close statement */
mysqli_stmt_close($stmt);
echo json_encode(array("result"=>$result), JSON_UNESCAPED_UNICODE);
}
else{
echo "Statement Prepare Error";
}
mysqli_close($con);
I already made the content of $tweetid and $body be printed inside the while statement as test and it works fine, meaning that the problem is not the query, but something with the array. What am I missing?
Thanks!
Try like this
$result = array();
while(mysqli_stmt_fetch($stmt)){
$result[] = array('Id'=>$tweetid,'Body'=>$body);
}
Demo :https://3v4l.org/XZOu5
I found the problem after some debugging. The problem was in the json_enconde function, which was silently failing because of JSON_ERROR_UTF8 type of error. I had some problems of special characters from my native language before I had success with just JSON_UNESCAPED_UNICODE before, but this time I added mysqli_set_charset($con, "utf8"); to the top of the code and it is now working. For the sake of completeness, the language is Brazilian Portuguese. The complete code is as follows.
$con = mysqli_connect(HOST,USER,PASS,DB);
mysqli_set_charset($con, "utf8");
$batch_sql = "select * from batchrecord";
$batch_res = mysqli_query($con,$batch_sql);
$row = mysqli_fetch_array($batch_res);
$batch_num = $row[0];
$start = $batch_num * 100;
$end = $start + 99;
if ($stmt = mysqli_prepare($con, "select tweetid, body from tweet where id >=
? and id <= ?")) {
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "ii", $start, $end);
/* execute query */
mysqli_stmt_execute($stmt);
/* bind result variables */
mysqli_stmt_bind_result($stmt, $tweetid, $body);
$result = array();
/* fetch value */
while(mysqli_stmt_fetch($stmt)){
$result[] = array('Id'=>$tweetid,'Body'=>$body);
}
/* close statement */
mysqli_stmt_close($stmt);
echo json_encode(array("result"=>$result), JSON_UNESCAPED_UNICODE);
}
else{
echo "Statement Prepare Error";
}
mysqli_close($con);
Thanks for Barclick Flores Velasquez for the help. I'm new in php and I didn't know there was print_r for debugging, it helped a lot finding the solution.

search function with prepared statement not displaying no result

When the search matches all displays perfectly. But when there is no match the no result message does not display. Please any insight on this one. Thanks upfront
$result = "SELECT T1.ID, T2.Image1, T1.unoone, T1.unotwo, T1.unothree,
T1.unofour
FROM T1 LEFT JOIN T2 ON (T1.ID=T2.Image1)
WHERE T1.ID=T2.Image1 AND T1.unoone LIKE '%".$uno_one."%'
AND T1.unotwo LIKE '%".$uno_two."%'
AND T1.unothree LIKE '%".$uno_three."%'
AND T1.unofour LIKE '%".$uno_four."%' ";
$stmt = mysqli_stmt_init($con);
$query = mysqli_stmt_prepare($stmt, $result);
if(!$query) {
die("no result");
} else {
/* execute statement */
mysqli_stmt_execute($stmt);
/* bind result variables */
mysqli_stmt_bind_result($stmt, $id, $img[0], $uno_one, $uno_two,
$uno_three, $uno_four);
/* fetch values */
while (mysqli_stmt_fetch($stmt)) {
echo $img[0];
echo $uno_one;
echo $uno_two;
echo $uno_three;
echo $uno_four;
}
/* close statement */
mysqli_stmt_close($stmt);
}
As Madan Sapkota said : "if(!$query) { only check if any error exists".
You need to use a function for counting results, like mysqli_stmt_num_rows():
if(mysqli_stmt_num_rows ( $stmt ) == 0 ){ echo "there is no result";}
// The while loop after won't be run when no result are found, no need to put an else here.
while (mysqli_stmt_fetch($stmt)) {
...
}

PHP link in search results not working correct

I have a little problem, I have been testing numbers of variants but I don´t get it to work.
I have a link in the search result.. (Full text search working)
> while($row = mysql_fetch_assoc($query)){
>
> $id = $row['id'];
>
> echo '<a href=profile1.php?id= . $row["id"] . >.INFO.</a>';
It shows INFO as a link and when i click on it, i jump to profile1.php but I´m not seeing any results, it is totaly blank page. the url I get is .../profile1.php?id=
Here is my profile.php
<?php
$mysqli = new mysqli("", "", "", ""); /* REPLACE NECESSARY DATA */
/* ESTABLISH CONNECTION */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$id=$_GET["id"];
if ($stmt = $mysqli->prepare("SELECT name, brand FROM table WHERE id=?")) {
$stmt->bind_param("d", $id); /* BIND DATA TO QUERY */
$stmt->execute(); /* EXECUTE QUERY */
$stmt->bind_result($name, $brand); /* BIND RESULT TO VARIABLE */
$stmt->fetch(); /* FETCH DATA */
printf("%s - %s", $name, $brand); /* ECHO DATA */
$stmt->close(); /* CLOSE STATEMENT */
}
$mysqli->close();
?>
I hope someone can help me.. Thanks!!!
Do this .
echo "<a href=profile1.php?id=$row[id]>INFO</a>";
or this.
echo '<a href=profile1.php?id='.$row['id'].'>INFO</a>'
Note:
You assigned your id to a variable, so better use that variable to the link. You should learn how to incorporate variables to your link.
Better use a single tick (') when using a variable inside. It's okay not to use single tick (') in your query IF the variable you are binding is an integer type.
Your link should look like this:
$id = $row['id'];
echo '<a href="profile1.php?id='.$id.'" >.INFO.</a>';
And your select query should look like this (profile1.php):
$sql ="SELECT * FROM table WHERE id='".$_GET["id"]."'";
It is also recommendable to use mysqli_* rather than the deprecated mysql_* API. Read here to learn more about SQL injections.
If you had it into mysqli_* prepared statement, it would look like this (profile1.php):
<?php
/* RE-ESTABLISH YOUR MYSQL CONNECTION */
$con = new mysqli("YourHost", "yourUsername", "YourPassword", "YourDB"); /* REPLACE NECESSARY DATA */
/* CHECK CONNECTION */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if ($stmt = $con->prepare("SELECT name, brand FROM table WHERE id = ?")){
$stmt->bind_param("i", $_GET["id"]); /* PARAMETIZE GET ID TO QUERY */
$stmt->execute(); /* EXECUTE QUERY */
$stmt->bind_result($name, $brand); /* BIND RESULT TO VARIABLE */
$stmt->fetch(); /* FETCH DATA */
printf("%s - %s", $name, $brand); /* ECHO DATA */
$stmt->close(); /* CLOSE STATEMENT */
}
$con->close();
?>

Why I can't get bind_result working and assign some of the values to a session?

I have made a prepared statement, supposed to login a user, everything works just fine, but I'm facing a problem with bind_result(). What I mean is that it is not working at all and I can't get the query's result and assign it to the SESSION
Here is my code:
session_start();
$sesUsername = "";
$sesCid = "";
$sesFirstName = "";
$sesLastName = "";
$mysqli = new mysqli($host_l, $username_l, $password_l, $dbName_l);
$loginQuery = "SELECT username, cid, first_name, last_name FROM Users WHERE username=? and password=?";
if($stmt = $mysqli->prepare($loginQuery)){
$stmt->bind_param('ss',$usernameEsc, $passwordEsc);
$stmt->execute();
/* Store the result (to get properties) */
$stmt->store_result();
/* Get the number of rows */
$num_of_rows = $stmt->num_rows;
/* Bind the result to variables */
$stmt->bind_result($sesUsername, $sesCid, $sesFirstName, $sesLastName);
if($num_of_rows == 1){
$_SESSION['username']= $sesUsername; // This is not working
return true;
}
else {
http_response_code(401);
}
/* free results */
$stmt->free_result();
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
The code redirects me to the members area, but in there the session variable username is empty.
Why I can't get it working? I know that I'm missing something really small, but as a newbie, I can't spot the problem.
You have to do:
$stmt->fetch();
to get the results into the variables.
try this:
$stmt->bind_result($sesUsername, $sesCid, $sesFirstName, $sesLastName);
while ($stmt->fetch()) {
$_SESSION['username']= $sesUsername;
}

Returning True or False on Prepared Statements

I just started learning mysqli (20 minutes ago) and I'm confused on something. In the example below I'm able to insert data into the server. How would I make the function return true on success and false on failure. Is it as simple as replacing return true on if the if statement is true and return false on the else statement or is it more advanced than that? What would I have to write if I wanted to return true on success and false on failure?
function insert($firstName, $lastName) {
if ($stmt = $mysqli->prepare("INSERT INTO CodeCall (FirstName, LastName) values (?,
?)")) {
/* Bind our params */
$stmt->bind_param('ss', $firstName, $lastName);
/* Execute the prepared Statement */
$stmt->execute();
/* Echo results */
echo "Inserted {$lastName},{$firstName} into database\n";
/* Set our params for second query */
$firstName = "John";
$lastName = "Ciacia";
/* Execute second Query */
$stmt->execute();
return true;
/* Close the statement */
$stmt->close();
}
else {
/* Error */
return false;
}}
When you execute your INSERT query (also UPDATES and DELETES queries) using execute method, it returns TRUE on success and FALSE on failure.
So you could do something like this:
function insert($firstName, $lastName) {
$stmt = $mysqli->prepare("INSERT INTO CodeCall (FirstName, LastName) values (?, ?)");
/* Bind our params */
$stmt->bind_param('ss', $firstName, $lastName);
/* Execute the prepared Statement */
if ( $stmt->execute() ) {
/* Echo results */
echo "Inserted {$lastName},{$firstName} into database\n";
/* Set our params for second query */
$firstName = "John";
$lastName = "Ciacia";
/* Execute second Query */
$stmt->execute();
$result = true;
} else {
/* Error */
$result = false;
}
/* Close the statement */
$stmt->close();
return $result;
}

Categories