PHP: Separate MySQL query values with a comma - php

I have a MySQL query like this written in PHP:
$merkki = $_GET["merkki"];
// Retrieve all the data from the table
//to show models based on selection of manufacturer
$result = mysql_query("SELECT * FROM Control_Mallit WHERE merkki_id = $merkki")
or die(mysql_error());
echo '{';
while($row = mysql_fetch_array($result)){
echo '"' . $row['id'] . '"' . ":" . '"' . $row['malli'] . '"';
}
echo '}';
Result is correct, but how I can get a comma after each record? If I echo (,) after each row my code doesn't work. I need it formatted as described below.
{
"":"--",
"series-1":"1 series",
"series-3":"3 series",
"series-5":"5 series",
"series-6":"6 series",
"series-7":"7 series"
}
What's the best way to do this?

Immediately stop using your code. It is vulnerable to SQL injection. Think of what would happen if the value of merkki was 1 OR 1=1. The statement would return all records:
SELECT * FROM Control_Mallit WHERE merkki_id = 1 OR 1=1
You need to bind parameters to your query using mysqli_ or PDO functions (mysql_ functions are being deprecated. Also, use a column list and do not SELECT *.
Here is a possible solution using mysqli_ (not tested):
<?php
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'world');
/* check connection */
if (!$link) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$array = array();
/* create a prepared statement */
$stmt = mysqli_prepare($link, "SELECT id, malli FROM Control_Mallit WHERE merkki_id = ?");
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, 'i', $_GET[merkki]);
/* execute query */
$result = mysqli_stmt_execute($stmt);
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
$array[] = '"' . $row['id'] . '"' . ":" . '"' . $row['malli'] . '"';
}
/* free result set */
mysqli_free_result($result);
/* close connection */
mysqli_close($link);
echo '{' . implode(',', $array) . '}';
?>
Edit
Following your original code, this solution should work:
$merkki = $_GET["merkki"];
$array = array();
// Retrieve all the data from the table to show models based on selection of manufacturer
$result = mysql_query("SELECT * FROM Control_Mallit WHERE merkki_id = $merkki")
or die(mysql_error());
while($row = mysql_fetch_array($result)){
$array[] = '"' . $row['id'] . '"' . ":" . '"' . $row['malli'] . '"';
}
echo '{' . implode(',', $array) . '}';

Try:
$merkki = $_GET["merkki"];
$merkki = mysql_real_escape_string($merkki);
// Retrieve all the data from the table to show models based on selection of manufacturer
$result = mysql_query("SELECT * FROM Control_Mallit WHERE merkki_id = $merkki")
or die(mysql_error());
$numRows = mysql_num_rows($result);
$row = 1;
echo '{';
while($row = mysql_fetch_array($result)){
echo '"' . $row['id'] . '"' . ":" . '"' . $row['malli'] . '"';
if ($row < $numRows) {
echo ',';
}
$row++;
}
echo '}';
It just uses the row count to determine if it should echo a comma or not based on whether or not it is on the last result.
Also, be sure to escape any input you pass to mysql queries or you are vulnerable to SQL injection. See about switching to PDO or Mysqli in the future.

I'd just stick everything in an array and use json_encode() to output it, eg
$data = array();
while ($row = mysql_fetch_array($result)) {
$data[$row['id']] = $row['malli'];
}
echo json_encode($data);
Small example here - http://codepad.viper-7.com/My27XJ
Also, you should not be using the deprecated mysql extension. Instead, I recommend PDO, eg
$db = new PDO(/* connection details */);
$stmt = $db->prepare('SELECT id, malli FROM Control_Mallit WHERE merkki_id = ?');
$stmt->bindParam(1, $_GET['merkki']);
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
// and so on

Related

How to remove 5 characters from the end of every column in a table MySQLi

I'm trying to loop through every row in a table, and remove 5 characters from the end of one column. I have written the following code but it seems to remove 2 characters for some reason.
<?php
$connection = new mysqli('localhost', 'nawd_test', 'password', 'nawd_test');
if ($connection->connect_errno > 0) {
die ('Unable to connect to database [' . $connection->connect_error . ']');
}
$sql = "SELECT *
FROM test";
if (!$result = $connection->query($sql)) {
die ('There was an error running query[' . $connection->error . ']');
}
//Create an array to hold the values of id's already changed
$ids = [];
$newVals = [];
echo '<p>Fetching rows...</p>';
while ($row = $result->fetch_assoc()) {
//Check / Add the id
if (in_array($row['id'], $ids)) {
echo '<p style="red"><strong>Error: Script has repeated itself!</strong></p>';
break;
}
$ids[] = $row['id'];
$rowName = $row['name'];
$newName = substr($rowName, -1);
$newName = rtrim($rowName,$newName);
$newVals[] = $newName;
}
//Now loop and update
$newValID = 0;
foreach ($ids as &$id) {
echo '<p>Updating row with ID ' . $id . '</p>';
mysqli_query($connection, "UPDATE test SET name ='" . $newVals[$newValID] . "' WHERE id=" . $id);
echo '<p>Column successfully changed "<em>' . $newVals[$newValID] . '</em>"</p>';
$newValID++;
}
echo '<p style="color: green;"><strong>Script complete!</strong></p>';
?>
Dont do this in php, you can do it with a single sql query:
UPDATE test SET name = LEFT(name, LENGTH(name) - 5)
Change
$newName = substr($rowName, -1);
$newName = rtrim($rowName,$newName);
into
$newName = substr($rowName, 0, strlen($rowName) - 5);
With the way you're working, you could never predict how many characters that would have removed at the end.
Minimum 1, maximum the whole word.
Please read the documentation about rtrim and substr.
try this if you wanna doit inside the query:
update table1 set name=substr(name,-5,length(name))

SQL Connection creates excessive concurrent HTTP connections to the host

I kept commenting parts of my PHP script till this is what I ended up with. This thing creates about 200 to 300 concurrent connections in under a minute to the SQL ip (checked from the gateway) and I don't understand why.
Shouldn't closing the SQL connection end the communication between the servers?
The php script is being called once a second via JavaScript, I'm the only user on the website.
PHP implementation of the sock (taken from the net, fclose() added as that's how I read socks are closed)
<?php
$cookie="tD2h6";
$data = $_COOKIE[$cookie];
parse_str($data, $output);
$name = $output['name'];
$pass = $output['pass'];
$con=mysqli_connect("89.33.242.99","global","changeme","global");
$sql = 'SELECT * FROM `users` WHERE `username`=?';
# Prepare statement
$stmt = $con->prepare($sql);
if($stmt === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $con->errno . ' ' . $con->error, E_USER_ERROR);
}
# Bind parameters. Types: s = string, i = integer, d = double, b = blob
$stmt->bind_param('s', $name);
# Execute statement
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();
if($row['password']===$pass && !empty($pass))
{
$hisusername = $name;
$hiscredits = $row['credits'];
$hiseuro = $row['euro'];
}
else
{
$hisusername = "Guest";
$hiscredits = "0";
$hiseuro = "0";
}
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM `users`");
$num_rows = mysqli_num_rows($result);
$result = mysqli_query($con,"SELECT * FROM `users` WHERE admlevel>0");
$num_admrows = mysqli_num_rows($result);
$data = array();
$i=1;
$result = mysqli_query($con,"SELECT * FROM jbchat ORDER BY id DESC LIMIT 7");
while($row = mysqli_fetch_array($result))
{
$data[$i] = $row['string'];
$i=$i+1;
}
for($i=7;$i>0;--$i)
{
$jbchat = $jbchat . $data[$i] . "<br>";
}
unset($data);
$data = array();
$i=1;
$result = mysqli_query($con,"SELECT * FROM frchat ORDER BY id DESC LIMIT 7");
while($row = mysqli_fetch_array($result))
{
$data[$i] = $row['string'];
$i=$i+1;
}
for($i=7;$i>0;--$i)
{
$frchat = $frchat . $data[$i] . "<br>";
}
unset($data);
$data = array();
$i=1;
$result = mysqli_query($con,"SELECT * FROM drchat ORDER BY id DESC LIMIT 7");
while($row = mysqli_fetch_array($result))
{
$data[$i] = $row['string'];
$i=$i+1;
}
for($i=7;$i>0;--$i)
{
$drchat = $drchat . $data[$i] . "<br>";
}
unset($data);
$data = array();
$i=1;
$result = mysqli_query($con,"SELECT * FROM cschat ORDER BY id DESC LIMIT 7");
while($row = mysqli_fetch_array($result))
{
$data[$i] = $row['string'];
$i=$i+1;
}
for($i=7;$i>0;--$i)
{
$cschat = $cschat . $data[$i] . "<br>";
}
$today = getdate();
$date = $today['mday'] . "/" . $today['mon'] . "/" . $today['year'];
if($today['minutes']>9)
$time = $today['hours'] . ":" . $today['minutes'];
else
$time = $today['hours'] . ":0" . $today['minutes'];
$sqlx = 'SELECT * FROM notifications WHERE username=? ORDER BY id DESC LIMIT 5';
# Prepare statement
$stmt = $con->prepare($sqlx);
if($stmt === false) {
trigger_error('Wrong SQL: ' . $sqlx . ' Error: ' . $con->errno . ' ' . $con->error, E_USER_ERROR);
}
# Bind parameters. Types: s = string, i = integer, d = double, b = blob
$stmt->bind_param('s', $name);
$stmt->execute();
$res = $stmt->get_result();
while($row = $res->fetch_assoc())
{
if($row['read']==0)
$nnumber = $nnumber+1;
$notifications = $notifications . "
<li>
<a href=\"#\" onclick=\"invisphp2('http://r4ge.ro/php/readnotif.php?notifid=" . $row['id'] . "')\">
<i class=\"fa fa-warning danger\"></i>" . $row['text'] . "
<br>" . $row['date'] . "
</a>
</li>";
}
$result = mysqli_query($con,"SELECT * FROM chat ORDER BY id DESC LIMIT 30");
$data = array();
$i=1;
while($row = mysqli_fetch_array($result))
{
$data[$i] = $row['name'] . ": " . $row['msg'];
$i=$i+1;
}
for($i=30;$i>0;--$i)
{
$lchat = $lchat . $data[$i] . "<br>";
}
echo json_encode(array(
"registered" => $num_rows,
"admins" => $num_admrows,
"time" => $time,
"date" => $date,
"nnumber" => $nnumber,
"notifications" => $notifications,
"lchat" => $lchat,
"hisusername" => $hisusername,
"hiscredits" => $hiscredits,
"hiseuro" => $hiseuro
));
mysqli_close($con);
?>
Edit: after listening to a comment that's now deleted, I removed every single query except the first one, so this code is now being ran, the connections still rocketed to 150 in 20-30 seconds.
<?php
$cookie="tD2h6";
$data = $_COOKIE[$cookie];
parse_str($data, $output);
$name = $output['name'];
$pass = $output['pass'];
$con=mysqli_connect("89.33.242.99","global","changeme","global");
$sql = 'SELECT * FROM `users` WHERE `username`=?';
# Prepare statement
$stmt = $con->prepare($sql);
if($stmt === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $con->errno . ' ' . $con->error, E_USER_ERROR);
}
# Bind parameters. Types: s = string, i = integer, d = double, b = blob
$stmt->bind_param('s', $name);
# Execute statement
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();
if($row['password']===$pass && !empty($pass))
{
$hisusername = $name;
$hiscredits = $row['credits'];
$hiseuro = $row['euro'];
}
else
{
$hisusername = "Guest";
$hiscredits = "0";
$hiseuro = "0";
}
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
echo json_encode(array(
"registered" => $num_rows,
"admins" => $num_admrows,
"time" => $time,
"date" => $date,
"nnumber" => $nnumber,
"notifications" => $notifications,
"lchat" => $lchat,
"hisusername" => $hisusername,
"hiscredits" => $hiscredits,
"hiseuro" => $hiseuro
));
mysqli_close($con);
?>
I know this will make me look very bad.
Unfortunately there is nothing bad in this particular code.
The problem was at a much deeper level in the site's framework, and the above code being the homepage, lead me to think it was the source of the problem.
To #developerwjk , the answer is no, combining procedural and object oriented implementations has no effect whatsoever on the functionality of mysqli, it works great.
The culprit: lack of mysqli_close() at the end of every single PHP that creates a connection
Don't trust the documentation when it says the connection is closed on script end, put it there just to be safe.

Php script to export mysql table data to a csv, escaping data from certain columns and mapping strings to arrays?

I need to migrate data within our old bug tracker (Zentrack) to our new one and the only import method I can use is to import from CSV. To do so I need the data from two tables, tickets and logs so I wrote the script below in php.
<?php
error_reporting(E_ALL);
$host = "localhost";
$user = "dbuser";
$pass = "dbpass";
$db = "zentrk";
$users[1] = 'john';
$users[4] = 'sally';
$users[5] = 'nick';
$users[6] = 'ralph';
$r = mysql_connect($host, $user, $pass);
if (!$r) {
echo "Could not connect to server\n";
trigger_error(mysql_error(), E_USER_ERROR);
}
echo mysql_get_server_info() . "\n";
$r2 = mysql_select_db($db);
if (!$r2) {
echo "Cannot select database\n";
trigger_error(mysql_error(), E_USER_ERROR);
}
$query_tickets = "select ZENTRACK_TICKETS.id, ZENTRACK_TICKETS.title, ZENTRACK_TICKETS.priority, ZENTRACK_TICKETS.status, ZENTRACK_TICKETS.description, ZENTRACK_TICKETS.otime,
ZENTRACK_TICKETS.type_id, ZENTRACK_TICKETS.user_id, ZENTRACK_TICKETS.system_id, ZENTRACK_TICKETS.creator_id, ZENTRACK_TICKETS.proj_key
from ZENTRACK_TICKETS
where ZENTRACK_TICKETS.status = 'OPEN'
and ZENTRACK_TICKETS.system_id in ('18', '3', '6', '1', '16', '7', '9', '4', '20')
and ZENTRACK_TICKETS.type_id not in ('1', '10', '5')";
$rs = mysql_query($query_tickets);
if (!$rs) {
echo "Could not execute query: $query";
trigger_error(mysql_error(), E_USER_ERROR);
} else {
echo "Query: $query executed\n";
}
$export = array();
$export[] = 'id,title,created date,priority,type,assigned,description,system,creator,project key,log1,log2,log3,log4,log5,log6,log7,log8,log9,log10
';
while ($row = mysql_fetch_assoc($rs)) {
$line = '';
$count = 0;
$line .= $row['id'] . "," . $row['title'] . "," . date('d-M-y h:m a',$row['otime']) . "," . $row['priority'] . "," . $row['type_id'] . "," . $row['user_id'] . "," . $row['description'] . "," . $row['system_id'] . "," . $row['creator_id'] . "," . $row['proj_key'] . ",";
$logs = find_logs($id = $row['id']);
foreach($logs as $log_entry) {
$line .= $log_entry.",";
$count++;
}
while($count < 10) {
$line .= ",";
$count++;
}
$export[] = $line.'
';
}
mysql_close();
// print_r($export);
$file = 'tickets.csv';
file_put_contents($file, $export);
function find_logs($ticket) {
$content = array();
$query = "select ZENTRACK_LOGS.created, ZENTRACK_LOGS.user_id, ZENTRACK_LOGS.entry
from ZENTRACK_LOGS
where ZENTRACK_LOGS.ticket_id = $ticket
and ZENTRACK_LOGS.action <> 'EDIT' ";
$rs = mysql_query($query);
if (!$rs) {
echo "Could not execute query: $query";
trigger_error(mysql_error(), E_USER_ERROR);
}
while ($row = mysql_fetch_assoc($rs)) {
$date = date('d-M-y h:m a',$row['created']);
$content[] = $date . ";" . $row['user_id'] . ";" . $row['entry'];
}
return $content;
}
?>
I'm running into two problems with this script, that I'm sure are due to me being new to PHP.
1) I need to escape out the data in $row['description'] as it contains both carriage returns and , in the text that is incorrectly breaking the output into new rows when saved to CSV. I need to save the contents of this row within " " but I'm not sure how to do so.
2) The data returned in $row['user_id'], $row['creator_id'] and $row['user_id'] within the find_logs function returns a number, which I need to find that number and replace with the corresponding string in the $users array. What's the best way to do this?
When dealing with csv files use fgetcsv and fputcsv, provide it with an array and it will handle the escaping for you.

Convert mysql_query to PDO statements

While there are a large number of PDO usage examples I have not been able to successfully convert from mysql_query to PDO statements.
Here's what works but is insecure:
<?php
$db = mysql_connect("localhost","username","passphrase");
mysql_select_db("database",$db);
$cat= $_GET["cat"];
/* grab a row and print what we need */
$result = mysql_query("SELECT * FROM cat WHERE cat = '$cat' ",$db);
$myrow3 = mysql_fetch_row($result);
echo "$myrow3[2]";
/* here's an array */
echo '<div class="container">';
$q = mysql_query("SELECT * FROM name WHERE Field4 = '$cat'",$db);
while ($res = mysql_fetch_array($q)){
echo '<div class="item"><p>' . $res['Field1'] . '</p></div>';
}
echo '</div>';
?>
Here is my attempt thus far at attempting to convert the mysql_query* to PDO statements based on How to prevent SQL injection in PHP?. Currently the page does not display, well anything. Any insight would be appreciated!
<?php
$pdo = new PDO('mysql:host=localhost;dbname=database','username','password');
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$cat= $_GET["cat"];
/* let try grabbing one of those rows, do not think an array should be here? */
$stmt = $pdo->prepare('SELECT * FROM cat WHERE cat = :cat');
$stmt->bindParam(':cat', $cat);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
echo $result[2];
/* Now we need an array similar to what we had before */
echo '<div class="container">';
$stmt = $pdo->prepare('SELECT * FROM name WHERE Field4 = :Field4');
while ($res = $stmt->execute(array(':cat' => $cat))) {
echo '<div class="item"><p>' . $res['Field1'] . '</p></div>';
}
echo '</div>';
?>
The way you are doing it, first off, isn't protecting you.
A PDO statement should look like (from the manual):
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);
So, for your example:
$stmt = $pdo->prepare('SELECT * FROM cat WHERE cat = :cat');
$stmt->bindParam(':cat', $cat);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
Or you could do:
$stmt = $pdo->prepare("SELECT * FROM cat where cat = ?");
if ($stmt->execute(array($cat)) {
while ($row = $stmt->fetch()) {
//print stuff or whatever
}
}
Finally, in your last part:
while $stmt->execute(array(':cat' => $cat));
echo '<div class="item"><p>' . $res['Field1'] . '</p></div>';
It doesn't look like $res ever gets set. It should look like:
while ($res = $stmt->execute(array(':cat' => $cat)) {
echo '<div class="item"><p><a href="bits.php?page=' . $res['Field2'] .
'&' . $res['Field6'] . '">' . $res['Field1'] . '</a></p></div>';
}

Display database fields as checkboxes

I'm trying to display all my database fields like radio buttons. For example I have this database fields :
hostess_id
hostess_name_en
hostess_surname_en
... etc ...
I want to display them as radio buttons, in order to select them, then display data information only for the selected buttons.
How can I do that?
I have something like this:
<?php
$link = mysql_connect('localhost', 'root', '');
if (!$link) {
die('Could not connect to MySQL server: ' . mysql_error());
}
$dbname = 'db_up';
$db_selected = mysql_select_db($dbname, $link);
if (!$db_selected) {
die("Could not set $dbname: " . mysql_error());
}
$res = mysql_query('select * from hostess', $link);
while ($row = mysql_fetch_assoc($result)){
echo "<td><input type=\'checkbox\' name=\'hostess[]\' value=\'" . $row['hostess_id'] . "\'>" . $row['hostess_firstname_en'] . "<br />";
}
?>
With PDO, It will get all fields
$q = $dbh->prepare("DESCRIBE tablename");
$q->execute();
$table_fields = $q->fetchAll(PDO::FETCH_COLUMN);
With deprecated mysql_*
function mysql_field_array( $query ) {
$field = mysql_num_fields( $query );
for ( $i = 0; $i < $field; $i++ ) {
$names[] = mysql_field_name( $query, $i );
}
return $names;
}
// Example of use
$fields = mysql_field_array( $query );
Than you can loop through that array of field names and use the name with your check box.
Checkboxes need a unique name or they need to be an array. A checkbox array would be appropriate for what you're doing:
while ($row = mysql_fetch_assoc($result)){
echo "<input type='checkbox' name='hostess[]' value='" . $row['id'] . "' />" . htmlentities($row['hostess_surname_en']) . "<br />";
}
This will give you a list of checkboxes with the hostess surname next to each.
Now, when this form is submitted to a PHP script, you will be able to access the selected row id's with:
$selectedIds = $_POST['hostess']; // an array
$selectedIds is an array of the checked record ids.
I suggest using PDO or MySQLi for new code because the mysql_* library is deprecated.

Categories