I have the following code with my php(updated):
$sql = "INSERT INTO uac_user (user_name, user_password, create_time, lastupdateTime) VALUES ('$usernmae', '$password', NOW(), NOW())";
if ($conn->query($sql) === TRUE) {
$last_id = $conn->insert_id; //get new id
$records = array(); //select role
if($result = $conn->query("SELECT role_id FROM uac_role WHERE `role_name` = '$role';")){
if($result->num_rows){
while ($row = $result->fetch_object()){
$records = $row;
}
$dateResult=(string)json_encode($records);
echo ($dateResult);
echo ($dateResult['role_id']);
// $sql2 = "INSERT INTO uac_mapping (role_id, user_id) VALUES ('$dateResult['role_id']', '$last_id')"; //insert mapping
// if ($conn->query($sql2) === TRUE) {
// echo "success";
// }
// else {
// echo "Error: " . $sql . "<br>" . $conn->error;
// }
}
else $records = 'no data';
}
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
die();
the first echo return [{"role_id":"4"}]
but the second return [
what I need for the second one is 4
what is the problem about my code?
I think you have made a common mistake of confusing what JSON is and is not. JSON is a way of representing some data in a string, for transfer to another system, where it will be turned back into something else for use. JSON is not a type of object that you can use directly to extract data.
Look carefully at this line:
$dateResult=(string)json_encode($records);
The result of this is that $dateResult is a string - you even have an extra (string), but even without that, the manual page for json_encode makes clear that you will always have a string:
Returns a string containing the JSON representation of the supplied value.
You then run this:
$dateResult[role_id]
You are trying to look up role_id inside a string. But a string is just a bunch of symbols, it doesn't know what "role_id" is. You had structured data in $records, it's there that you want to look up role_id.
If $records is an array, what you want is $records['role_id'] (note the quotes around 'role_id'; role_id would be the name of a constant, not a string).
If $records is an object, what you want is $records->role_id (no quotes this time, because ->role_id is more like a variable name than a string).
Your json is probably an array of objects, so you can loop through them and use something like:
echo $dateResult[$counter]->role_id;
//$counter will be your loop incrementer;
Related
I am populating a MySQL database using PHP and SQL languages. The table I am populating is called project. After I add the record to project, I would like to send out an email including the project_id and project_title. I thus need to know the project_id after I populate the project table.
The command: $sql = "SELECT LAST_INSERT_ID()"; is returning an array. I have tried several guesses of what is in the array, without any luck.
public function add_project($project_title, $project_description,
$skill_cat_id, $name_id) {
$dbConn = new DatabaseConn();
$this->name_id = $name_id;
$this->skill_cat_id = $skill_cat_id;
if($this->check_for_duplicates() != null) {
$message = "This Project already exist!";
echo "<script type='text/javascript'>alert('$message');</script>";
} else {
$sql = "INSERT INTO project "
. "(project_id, project_title, project_start_date, "
. "project_description, skill_cat_id, volunteer_id, response_id, name_id) "
. "VALUES (DEFAULT, $project_title, DEFAULT, "
. "$project_description, $skill_cat_id, DEFAULT, DEFAULT, $name_id)";
try {
$dbConn->exec($sql);
}
catch(PDOException $e) {
$message = $sql . "<br />" . $e->getMessage();
echo "<script type='text/javascript'>alert('$message');</script>";
}
$dbConn2 = new DatabaseConn();
$sql = "SELECT LAST_INSERT_ID()";
try {
$statement = $dbConn2->prepare($sql);
$statement->execute();
$result = $statement->fetch();
$statement->closeCursor();
}
catch(PDOException $e) {
$message = $sql . "<br />" . $e->getMessage();
echo "<script type='text/javascript'>alert('$message');</script>";
}
return $result;
}
}
I am expecting the project_id of the project table, yet the command is returning an array.
PDOStatement::fetch() always returns an array, which is one row of the result set. The array is either an ordinal array or a hash array indexed by column name.
It doesn't matter that your query is guaranteed to have one column and one row. It's still a result set, for which fetch() returns an array. The array it returns will have one entry, corresponding to the single column of your query.
If you want to return just one column as a scalar, try PDOStatement::fetchColumn().
See the documentation for description and a code example.
You can get last insert Id from the pdo object itself. https://www.php.net/manual/en/pdo.lastinsertid.php
This question already has answers here:
How to check if a row exists in MySQL? (i.e. check if username or email exists in MySQL)
(4 answers)
Closed 5 years ago.
Ok so basically I'm trying to create a simple web app
I want to check if one element is inside the table, and if inside I want to return a boolean value, like for example if "abc" is inside the table named "name" then return YES.
Here's my code, not working:
error_reporting(E_ALL);
$mysql = mysqli_connect(/* PRIVATE DATA */) or die ("ERROR CONNECTING TO THE DB");
if(isset($_POST['submit'])) {
$theAddress = $_POST['youtubeURL'];
$result = "SELECT * FROM data WHERE youtubeURL = '" . $theAddress . "'";
$query = mysqli_query($mysql, $result);
if (!$query) {
printf("Error");
} else {
printf("NO ERROR");
}
AND HERE'S THE NON-WORKING PART :
while($row = mysqli_fetch_array($query)) {
if ($row == 0) {
echo "NO RESULT LIKE THIS";
}else {
echo "AT LEAST ONE RESULT LIKE THIS";
}
}
}
First, learn to use parameters queries. They really are no harder to use than stuffing a string value into a query.
Second, if you want to know if something exists, then write the query just to do that. The simplest query is probably:
SELECT EXISTS (SELECT 1 FROM data WHERE youtubeURL = ?) as exists_flag
This will return 1 if something matches. Just run the query and read the single value that is returned.
Note that returning select * to check for existence is an anti-pattern. You are returning way more data from the database than you need (both in terms of rows and columns). That is usually not a good idea.
It should be like this.
//in case you want to see total of the wors
if(mysqli_num_rows($query) == 0) {
echo "NO RESULT LIKE THIS";
} else {
echo "AT LEAST ONE RESULT LIKE THIS";
}
//in case you want to check for each of the row
while($row = mysqli_fetch_array($query)) {
if (empty($row)) {
echo "NO RESULT LIKE THIS";
} else {
echo "AT LEAST ONE RESULT LIKE THIS";
}
}
You need to use mysqli_num_rows to count the rows ..
$result = "SELECT * FROM data WHERE youtubeURL = '" . $theAddress . "'";
$query = mysqli_query($mysql, $result);
if(mysqli_num_rows($query)) {
echo "AT LEAST ONE RESULT LIKE THIS";
} else {
echo "NO RESULT LIKE THIS";
}
I am making an API call to retrieve user_name's from my database.
My first step is to make a call to retrieve all the player_id's. They are stored in $communityPlayersIds and currently output as below:
["2","31","31","32"]
I now want to make a second call to the database to fetch the user_name's of the id's that match.
$communityPlayerNames = array();
$communityPlayerNames = $dao->getPlayerNames($communityPlayersIds);
I have looked into it and seen I should use an IN command something like this:
public function getPlayerNames($player_ids)
{
$returnValue = array();
$sql = "SELECT user_name\n"
. "FROM users\n"
. "WHERE id IN ( '".$player_ids."')";
$result = $this->conn->query($sql);
if($result != null && (mysqli_num_rows($result) >= 1)){
while($row = $result -> fetch_array(MYSQLI_ASSOC)){
if(!empty($row)){
$returnValue[] = $row;
}
}
}
return $returnValue;
}
}
However this isn't working and returns this:
[{"user_name":null}]
If I echo ($sql) I get this:
SELECT user_name FROM users WHERE id IN ( '2,31,31,32')
Which looks correct does it not?
Where am I going wrong?
You essentially want your final query to look like this
Select user_name from users where id in (2,31,31,32) -- dupe 31 does no harm
Make sure your series of IDs are inside parentheses IN ($player_ids) and not just a single quote IN '$player_ids'
You can try building the IN-part of the SQL like this:
$returnValue = array();
$in_statement = "(";
foreach($player_ids as $player_id)
{
$in_statement = $in_statement.$player_id->player_id.",";
}
rtrim($in_statement, ",");
$in_statement = $in_statement.")";
$sql = "SELECT community_players.player_id\n"
. "from community_players\n"
. "where community_players.community_id in ".$in_statement."";
So just the middle-part is new, where the $in_statement gets build. And in your SQL you have to change the "=" to "IN". You can generate the IN-part shorter, but this way you can easier see how it's done, so you can fit it to your needs.
in your code you put ' after in which shows syntax error.
You can try
Assuming your
$communityPlayersIds has below value as array:
["2","31","31","32"]
if its not an array then convert it using json_decode()
and then try below query
$sql = "SELECT community_players.player_id\n"
. "from community_players\n"
. "where community_players.community_id IN (".join(",",$communityPlayersIds).")";
I am trying to add dynamic array values from two arrays into mysql table as columns, several rows at a time. I have created a loop for that.
When I run it it produces an error, stating that I have an error in MYSQL syntax. When I try to run the query statement that is produced directly in phpMyAdmin it runs fine. So the syntax shouldn't be an issue. Thanks for any help.
function addSystemDataTanks ($db, $tankNamesArray, $tankVolumesArray)
{
global $tankNamesArray;
global $tankVolumesArray;
global $noOfTanks;
$statement = "replace into tanks (TANK_NAME, TANK_VOLUME) ";
$statement .= "values ";
for ($i = 0; $i < $noOfTanks; $i++) {
$statement.= "('".$tankNamesArray[$i]."', '".$tankVolumesArray[$i]."'), ";
}
$statement.= rtrim($statement, ',');
$result = mysqli_query($db, $statement);
if ($result)
{
return true;
}else{
$errno = mysqli_errno($db);
echo "{h4}MySQL Error No: ".mysqli_errno($db)."</h4>";
echo "{h4}MySQL Error: ".mysqli_error($db)."</h4>";
echo "{h4}SQL: ".$statement."</h4>";
echo "{h4}MySQL Affected Rows: ".mysqli_affected_rows($db)."</h4>";
}
return 'NotAdded';
}
I see two problems so far:
First: where are you assigning a value to $noOfTanks ? your for loop depends on that value, however, i don't see it being assigned which means it is currently resulting in NULL, thus your loop not iterating.
Second: This line $statement .= rtrim($statement, ','); is concatenating to the original $statement variable thus ending up with this:
'REPLACE INTO tanks (TANK_NAME, TANK_VOLUME) values REPLACE INTO tanks (TANK_NAME, TANK_VOLUME) values '
I'm assuming you want to re-assign after your trim, in that case do this:
$statement = rtrim($statement, ',');
This is pretty straight forward.
EDIT: Updated question and added fourth echo.
Here is PHP code:
<?php
$ratings="3";
$item="Inception";
$query="SELECT * FROM items WHERE item = '". $item ."' LIMIT 1";
echo $query;
echo "<br />";
$result=mysql_query($query);
echo $result;
echo "<br />";
while ($row = mysql_fetch_array($result)) {
$item_id = $row['item_id'];
echo $item_id;
echo "<br />";
}
$query_two = "INSERT INTO ratings (rating, item_id), VALUES (' {$ratings} ', ' {$item_id} ')";
echo $query_two;
$sql = mysql_query($query_two);
mysql_close();
?>
Here is web output with all the echo's:
SELECT * FROM items WHERE item = 'Inception' LIMIT 1
Resource id #7
INSERT INTO ratings (rating, item_id), VALUES (' 3 ', ' ')
How come my $item_id is blank? (third row underneath Resource id)
This part of code produces it:
$result=mysql_query($query);
echo $result;
It shows Resource... because it is of resource type, it's just a sort of special handler for query, it's not like normal type (string or int for example), so it has nothing readable to print.
If you want to print data from query then you must firstly fetch it.
Also note that those mysql_* functions are deprecated, it is discouraged to use them. Note from php manual:
Use of this extension is discouraged. Instead, the MySQLi or PDO_MySQL
extension should be used. See also MySQL: choosing an API guide and
related FAQ for more information. Alternatives to this function
include:
mysqli_query()
PDO::query()
This does not have anything to do with IDs from the database.
This (Result#7) says that this result resource is seventh resource to be created by your php script execution.
Also
$query_two = "INSERT INTO ratings (rating, item_id), VALUES (' {$ratings} ', ' {$item_id} ')";
should be
$query_two = "INSERT INTO ratings (rating, item_id) VALUES (' {$ratings} ', ' {$item_id} ')";
You have comma before VALUES.
Also, it seems that $item_id is blank. Please check DB whether you have data for item = 'Inception'.
Regarding, Result#7 please follow others answers.
The Resource ID is coming from the actual process/object that the MySQL Query is.
to return the result you need:
$row = mysql_fetch_array( $query );
echo $row['item']
You need to do something with the result resource. Try this:
$result=mysql_query($query);
//echo $result;
$result_array = mysql_fetch_assoc( $result );
print_r( $result_array );
EDIT: I see you updated your question.
You should run your item='Inception' query directly in MySQL to confirm that results are what you expect.
You cannot echo the result that simple. You need to fetch the result to for example an array:
while ($row = mysql_fetch_array($query)) {
echo $row['a_column'] . "<br />";
}
or an object:
while ($variable = mysql_fetch_object($query) {
$value = $variable->a_column;
}
echo $value;
There are more ways but this is just two examples