Pull Column Data with PDO - php

Okay I have been able to pull a random account and pull one account as long as I predefine it but now im curious as to how to pull a account based on the Account Number
So basicly if the account number matches pull all the data for that row.
$db = new PDO('mysql:host=' . $config['db']['host'] . ';dbname=' . $config['db'] ['dbname'], $config['db']['username'], $config['db']['password']);
$AccountNumber = "uwoi1002"
$query = $db->query("SELECT `content`.`ProfilePic` FROM `content`");
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$Hello = $row['ProfilePic'];
echo '<html><img src="http://www.MYDOMAIN.COM/Content/';
echo $Hello;
echo '"></html>';
}
?>
So what this is doing is returning everyones profile pics on one page Not quite what I want
I have it where in a feild on my mysql data base it has a unique Id for each account I would like it to randomly pic one of those then return all the data for that row
FirstName
LastName
Gender
City
State
FacebookUrl
BirthMonth
BirthDay
BirthYear
AccountNumber - This is the one I want to pull based on
ProfilePic
ProfilePicCaption
So basically pick a random row and pull all the data instead of displaying all the data for one column
Thank you any and all help is awesome and at least now im using secure code

It sounds like you jsut need a WHERE clause...
// the ?, called a placeholder will have the value substituted for it
$stmt = $db->prepare("SELECT `content`.`ProfilePic` FROM `content` WHERE id = ?");
// an array of values for the placeholders in the query
$stmt->execute(array(2));
while(false !== ($row = $stmt->fetch(PDO::FETCH_ASSOC))) {
// do stuff with data
}
Alternatively if you can use named placeholders which i would recommend if you have a query with lots of parameters:
// the :id, called a placeholder will have the value substituted for it
$stmt = $db->prepare("SELECT `content`.`ProfilePic` FROM `content` WHERE id = :id");
// an array of values for the placeholders in the query
$stmt->execute(array(':id' => 2));

Related

Displaying only selected values from database

<?php
$sql = "SELECT * FROM team;";
$result = mysqli_query($conn, $sql );
$row = mysqli_fetch_row($result);
$teamname = $row[1];
echo $teamname;
Consider table in DB consists of 10 names from 1-10. That will be displayed on the screen as usually (using retrieving), but the problem is when I click any name from 1-10 displaying on the screen that should open a new page by displaying only the particular name I selected.
I tried this but, all the values are displaying.
First, add to your mysql table a column called "ID" to associate a number to each name.
After you can direct the user to your page like this
Name n.1 // etc..
so you can take the id of your name using GET and display to your page only that name
(Always use Prepared Statement even when it is not strictly necessary)
PHP script
$name_id = $_GET['id'];
// connect to your db
$stmt = $db->prepare("SELECT * FROM team WHERE ID = ?");
$stmt->bind_param("s",$name_id);
$stmt->execute();
$result = $stmt->get_result()->fetch_assoc();
echo $result['name'];
if you need anything else, comment below.

Obtain record from MySQL strip tags then update

I have a field (Description) in a MySQL database (poi). I wish to use php and the strip_tags to remove the HTML from all the records in the database. I then want to update the result to the same Description field in the database.
I have no problem with obtain the string and stripping the HTML, but I just can't seem to work out how to update the database with the result.
// check connection
if(mysqli_connect_errno()) {
echo "Connection Failed: " . mysqli_connect_errno();
exit();
}
$sql_article = "SELECT Description FROM poi";
$result = $mysqli->query($sql_article);
// Iterates through the MySQL results
while ($row = $result->fetch_array())
{
$Description_no_html = strip_tags($row['Description']);
printf("%s<br />\n", $Description_no_html);
}
Ideally each row will have a unique id column that you can use to specify which row to update using a prepared statement:
$sql_article = "SELECT id, Description FROM poi";
$result = $mysqli->query($sql_article);
$stmt = $mysqli->prepare("UPDATE poi SET Description = ? WHERE id = ?");
// Iterates through the MySQL results
while ($row = $result->fetch_array())
{
$Description_no_html = strip_tags($row['Description']);
printf("%s<br />\n", $Description_no_html);
$stmt->bind_param("si",$Description_no_html,$row['id']);
$stmt->execute();
}
If you don't have a unique id column, then use the following statement instead
$stmt = $mysqli->prepare("UPDATE poi SET Description = ? WHERE Description = ?");
and
$stmt->bind_param("ss",$Description_no_html,$row['Description']);
Alternative: stripping tags directly in mysql
You can create a custom mysql function that strips tags (https://stackoverflow.com/a/13346684/3574819) and use the following query
UPDATE poi SET Description = strip_tags(Description)
Disclaimer: I'm not sure how well the above referenced mysql strip_tags works, so your mileage may vary depending on your content.

Returned results from JSON to insert into mysql table and then email the results

I need help with how to insert the returned results of a JSON array into an sql table and then email the results returned.
Below is my php script so far that successfully gets the results of a query into a JSON array
<?php
// set up the connection variables
$db_name = 'dbanme';
$hostname = 'host';
$username = 'username';
$password = 'password';
// connect to the database
$dbh = new PDO("mysql:host=$hostname;dbname=$db_name", $username, $password);
// a query get all the records from the users table
$sql = 'SELECT tabel1.id,table1.type FROM table1 LEFT JOIN table2 ON table1.id=table2.id WHERE table1.id NOT IN ( SELECT table2.id FROM table2)';
// use prepared statements, even if not strictly required is good practice
$stmt = $dbh->prepare( $sql );
// execute the query
$stmt->execute();
// fetch the results into an array
$result = $stmt->fetchAll( PDO::FETCH_ASSOC );
// count number of results returned in the array
$countresults = count($result);
echo $countresults;
if ( $countresults > 0 ) {
// convert to json
$json = json_encode( $result );
// decode the results returned and insert them into table 2
// email the results returned
}
else {
echo ' no results found';
}
?>
UPDATE :
Table 1 structure :
ID INT 10
Type VARCHAR 50
Table 2 structure :
ID INT 10
Type VARCHAR 50
I realised I dont need to encode result into JSON but I still cant get the code to get the results returned from an array and insert them into tabl2 and then email the results straight after.
First you have to tell us why you converted the results to json in the first place. You already have an array, you don't need a JSON string in your case.
Anyhow, you convert a JSON string back to an array like this:
$yourArray = json_decode($json)
Now you say you want to insert the data into table two. I don't know how your table looks like, but if I look at your code, I guess your sql would look something like this:
$sql = 'INSERT INTO table2(id, type) VALUES (:id, :type)';
So your code would look something like this:
$sql = 'INSERT INTO table2(id, type) VALUES (:id, :type)';
$stmt->bindParam(':id', $yourArray ['id']);
$stmt->bindParam(':type', $yourArray['type']);
$stmt = $dbh->prepare( $sql );
$stmt->execute();
If you want to send the results via mail, you just use the default mail function:
$to = 'RECIEVER#MAIL'
$subject = 'SUBJECT';
$message='Your values are: '.$yourArray ['id'].' - '.$yourArray['type'];
mail($to,$subject,$message);
If the default mail function doesn't work, your server may not allow it (sometimes for security reasons). In this case I recommend using a third party library like PHPMailer
Your question did not reveal many informations, I did the best I could but the code above is still more of a pseudocode.

How do i get the last ID's from the inserted data?

I have an option to send multiple rows into an table, i'm using an foreach to do that:
if (is_array($add['jobname'])) {
$insert = "INSERT INTO job_offers (job_category, status) VALUES ";
foreach ($add['job_name'] as $key => $value) {
$insertedval[] = "
('" . safe($add['job_category'][$key]) . "',
'" . safe($add['status'][$key]) . "')";
}
}
$insert .= implode($insertedval, ",");
$last_id = db_query($insert, '+id?'); //gets the last generated ID, its a function that i created, and working great.
The problem is that i want to get the last ID, and i'm getting, but i'm inserting multiple rows into the database, and i want to get the ID's from all the inserted values, because they are being sent at the same time.
I can't put the $last_id variable inside the foreach loop, what do i do?
ps: i'm using auto increment
Can you try something like this?
$db = new PDO("mssql:host=$host;dbname=$dbname, $user, $pass");
$db->beginTransaction();
$stmt = $db->prepare('INSERT INTO job_offers (job_category, status) VALUES (?, ?)');
$insertedIds = array();
foreach ($add['job_name'] as $key => $value) {
$stmt->execute($add['job_category'][$key], $add['status'][$key]));
$id = $db->lastInsertId();
array_push($insertedIds, $id);
}
$db->commit();
the ids should be in the insertedIds.
You can't.
Only by saving the the last index id before the inserted data, and than do it again after and select all the ids between that range.
SELECT ID FROM job_offers ID BETWEEN last-before-insert AND last-after-insert
You don't need a custom function to get the last insert id , there is already one built into both php mysqli and php PDO extensions .
As far I know , the last insert id is session aware , meaning you will get the last insert from the current insert requests only .
Get last inset id using PHP PDO
$pdo->lastInsertId();
Get last insert id using mysqli
$mysqli->insert_id;
$pdo and $mysqli are the connection variables

How do I input values into a mysql table using php when there is a restriction?

I'd like to insert data into a table only when certain values in that table's (sessionid) row match another variable. I am struggling to put together the INSERT statement. The approach I am taking: retrieve all the rows in the table that match the criteria (retailer=$retailer) and then iterate through those rows inputting the variable options into the sessionid table.
$retailer = $_GET['retailer'];
$options = $_GET['options'];
$session = session_id();
//mysql connection stuff goes here
$query = "
SELECT *
FROM `sessionid`
WHERE `retailer` = '$retailer'
";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
mysql_query("INSERT INTO sessionid (options) VALUES('$options')");
}
Is the syntax correct for me to do this? Thanks!
Are you maybe looking for the UPDATE command instead?
UPDATE sessionid
SET options = $options
WHERE retailer = $retailer
By the way, I would look in to using PDO as it's more secure than pushing $_GET values in a database.
$db = new PDO('mysql:host=localhost;dbname=MYDATABASE', 'username', 'password');
$db->prepare('UPDATE sessionid SET options = ? WHERE retailer = ?');
$db->execute(array($options, $retailer));
You can use the WHERE clause in mysql to do this. If you are changing an existing row, you actually want UPDATE, not INSERT.
UPDATE sessionid SET options=$options where retailer = $retailer

Categories