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
Related
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;
I'm trying to get somes fields of a DB to import in another DB. So, I've connected to my DB with mysqli.
$mysqli = new mysqli("localhost", "root", "password", "db_name");
if ($mysqli->connect_errno) {
echo "$mysqli->connect_errno";
} else {
echo "You're IN"."<br />";
}
Now, I select the PK of the table:
$emails = $mysqli->query("SELECT email FROM customers WHERE date_first_order IS NOT NULL AND date_first_download IS NOT NULL");
I know that I've an array at this moment in $emails. So, I use a foreach loop.
foreach($emails as $email) {
$email = $email["cl_email"];
$query_name = $mysqli->query("SELECT name FROM customers WHERE email = $email");
$query_lastname = $mysqli->query("SELECT lastname FROM customers WHERE email = $email");
echo $email." ".$query_name." ".$query_lastname."<br />";
}
Here is my problem, with the query_name and query_lastname vars I get an array, an not an String. So, How I can get the field that I'm looking for?
Thanks.
When using MySQLi you should use mysqli_result::fetch_assoc() if you want to get each row as an associative array. http://php.net/manual/en/mysqli-result.fetch-assoc.php
while ($row = $result->fetch_assoc()) {
printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}
I hope this is a string, and you should firstly place it into ''.
$relation= $mysqli->query("SELECT name, lastname FROM customers WHERE email = $email");
-----------------------------------------------------------------------------^------^
And fetch row.
$row = $relation->fetch_row());
Secondly, you can simply return from array the wanted key.
echo $email . " " . $row["name"] . " " . $row["lastname"] . "<br />";
As mentioned by #jonathon mysqli-result::fetch-assoc() should help you with this. Also, i don't see any reason you have to do these queries. I believe you can get the desired output into single query too :)
$query_name = $mysqli->query("SELECT email,name,lastname FROM customers WHERE date_first_order IS NOT NULL AND date_first_download IS NOT NULL");
while ($row = $query_name->fetch_assoc()) {
print $row['email'].$row['name'].$row['lastname'];
}
You could use implode(",",$yourvariable);
It changes your array to a string. you may want to separate the results with a comma or you can just put ("",$yourvariable);
Hope this helps!:)
output JSON is here .when i reload the second time it has new recodes.but when i update the first time it does not have recodes
<?php
try {
$dbh = new PDO('mysql:host=localhost;dbname=$db', "user", "pass");
foreach($dbh->query('SELECT * FROM `jos_jea_towns` LIMIT 0, 500 ') as $row) {
echo '<pre>' . json_encode($row, JSON_PRETTY_PRINT).'</pre>';
}
$insertObject = $dbh->prepare("INSERT INTO `jos_jea_towns` (id, value) VALUES (:id, :value)");
$insertObject->bindParam(':id', $id);
$insertObject->bindParam(':value', $value);
// insert one row
$id = 433;
$value = 'yyy';
$insertObject->execute();
// insert another row with different values
$id = 434;
$value = 'xxx';
$insertObject->execute();
// insert another row with different values
$id = 435;
$value = 'Samitha';
$insertObject->execute();
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
How is this PDO prepare working or is there any problem with my JSON file?
Well, you are selecting first, and updating later. So the first time, you select, before you've added the records, then you add the records.
On the second reload, you've already added the records (from the previous iteration), and so the inserted records are displayed.
To solve, insert first, and select after. That way you can see the changes you've just made.
I'm having trouble taking data from a table and using it to replace strings in html text. I need to retrieve the last 4 rows from the table, then using str_replace, automatically create hrefs. So one column is url, one is title, one is description, etc. Then I'll create 4 separate hrefs from each row. What I have so far will work for only the last result. How do I make it work for all 4?
$query = "SELECT * FROM LINKS ORDER BY id DESC LIMIT 4";
if(!$result = mysql_query($query)){
// query failed, handle the error here...
$errors[] = "A fatal error occurred and this page is non-functional at this time!";
trigger_error("Query failed: $query<br /> Due to: " . mysql_error()); // application error
} else {
// query worked
if(!mysql_num_rows($result)){
// no matching rows
$main_content .= "No rows were found!\n";
} else {
// query matched at least one row, use the results from the query here...
$row = mysql_fetch_assoc($result);
$title1 .= $row['title'];
$link1 .= $row['url'];
}
}
//string replace arrays
$placeholders = array('LINK1','LINK2', 'LINK3','LINK4');
$replacevals = array($link1, $link2, $link3, $link4);
//replace the areas of the template with the posted values
$page = str_replace($placeholders,$replacevals,$template);
I'd like to be able to output $title2, $link2, $title3, etc.
Easiest way to do so would be to do something like this:
...
// query worked
if(!mysql_num_rows($result)){
// no matching rows
$main_content .= "No rows were found!\n";
}
else {
$urls_array = Array();
// query matched at least one row, use the results from the query here...
while ($row = mysql_fetch_assoc($result))
{
$urls_array[] = "<a href='" . $row['url'] . "'>" . $row['title'] . "</a>";
}
}
Then you end up with an array of html links set to the $urls_array variable.
Use a loop with mysql_fetch_assoc(). Traditionally, a while loop.
Here's an example derived from the PHP docs:
while ($row = mysql_fetch_assoc($result)) {
echo $row['title'];
}
That should get you started. Welcome to StackOverflow.
Ok i got a problem now i want to display a data from the database and display it through a function now how do i do that??
like i have fetched a row from the database and its name is $row_field['data']; and it is correct now i have assigned a variable to it like this $data = $row_field['data']; now if i call it in a function it shows undefined variable even after i assigned it global in the function like this
function fun(){
global $data;
echo $data;
}
but if i assign it a value like 1 or 2 or anything it gets displayed without any error why is that so??
If it displays if you assign it a value like 1 or 2 while still in the global scope, then I can only assume that your database did not return the result you thought it did. Does the database value display if you echo it out outside of the function?
Global is evil. I dont know what you are trying to do, but why dont you just do the query in the function itself?
If you have a column named data and your php call was something like
$result = mysql_query("SELECT data FROM mytable");
while ($row_field = mysql_fetch_assoc($result, MYSQL_NUM)) {
...
}
Then you could replace ... with print $row_field['data'].
Else please provide a snippet of your code where you query the db and retrieve the result.
When learning php try to start with simple things. For example in order to get some data from a database follow the examples from php website.
<?php
$conn = mysql_connect("localhost", "mysql_user", "mysql_password");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("mydbname")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = "SELECT id as userid, fullname, userstatus
FROM sometable
WHERE userstatus = 1";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
// Note: If you put extract($row); inside the following loop, you'll
// then create $userid, $fullname, and $userstatus
while ($row = mysql_fetch_assoc($result)) {
echo $row["userid"];
echo $row["fullname"];
echo $row["userstatus"];
}
mysql_free_result($result);
If all this goes well go a little further change a little the while loop.
$myArray = array();
while ($row = mysql_fetch_assoc($result)) {
$myArray[] = $row;
}
mysql_free_result($result);
// now you can start playing with your data
echo $myArray[0];
Small steps...