database normalization do I need it [closed] - mysql

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I've read a lot about normalization and I still can't fully understand it/I'm not sure how to normalize this. This is how my database currently looks, does it even need to be normalized? If so, where do I even start?
http://i.imgur.com/L43fHS6.png this is what it currently looks like

You will want to have 1 row per user_ID so you can easily access all the data.
e.g. for your gameID 5002947 (row11) this needs to be split into the following:
id setup_id user_ID
5002947 997 563749
5002947 997 500243
5002947 997 536271
...
You have two options. Create a complex SQL query that will handle this (I can't supply this unfortunately but I'm sure others could) or use php.
PHP method
Select all rows and explode the userID into an array.
loop through this array and insert back into the database.
Depending on the number of rows and userIDs you have this may take a while to execute.
e.g.
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
$query = 'SELECT * FROM table';
$data = mysqli_query($mysqli, $query);
while($row = mysqli_fetch_array($data))
{
$data[] = array("gameid"=>$row['game_ID'], "setupid"=>$row['setup_ID'],"userid"=>str_getcsv($row['user_ID'])); /*And all your other information*/
}
for($i=0; $i<count($data); $i++) {
$gameid = $data[$i]['gameid'];
$setupid = $data[$i]['setupid'];
/*Other info you need*/
for ($x=0; $x<count($data[$i]['userid']);$x++) {
$userid = $data[$i]['userid'][$x];
if ($stmt = $mysqli->prepare("INSERT INTO newtable (game_ID, setup_ID, user_ID) VALUES (?, ?, ?)")) {
$stmt->bind_param('iii', $gameid ,$setupid ,$userid);
if (!$stmt->execute()) {
$stmt->close();
}
}
}
}

Related

ERROR: Could not able to execute INSERT INTO posts (username, image, news, subreddit, title) VALUES [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
After creating a post and comment system, I added image uploading and got this error message
ERROR: Could not able to execute INSERT INTO posts (username, image, news, subreddit, title) VALUES ('testing1', 'koth.gif' test', 'm', 'Image'). You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'test', 'm', 'Image')' at line 1
I tried modifying the order of the INSERT command and also tried fixing it by changing the image upload code. Lastly, I checked to see if the uploads folders permissions were correct. My goal is to get the image to upload with my post.
Code section that is giving me the error:
$username = $_SESSION['userID'];
$title = mysqli_real_escape_string($link, $_REQUEST['title']);
$content = mysqli_real_escape_string($link, $_REQUEST['content']);
// Get image name
$image = $_FILES['image']['name'];
$target = "uploads/".basename($image);
//$subreddit = mysqli_real_escape_string($link, $_REQUEST['subreddit']);
$subreddit = 'm';
$posttype = '1';
if ($title === '' || $content === '') {
echo '<script>document.getElementById("failure").innerHTML = "<p>Title or post content not entered.</p>";</script>';
} else {
// attempt insert query execution
$sql = "INSERT INTO posts (username, image, news, subreddit, title) VALUES ('$username', '$image' $content', '$subreddit', '$title')";
if(mysqli_query($link, $sql)) {
// echo "Records added successfully.";
$msg = 'Post submitted successfully!';
echo "<script> window.location.assign('m.php'); </script>";
Missing quote and comma
INSERT INTO posts (username, image, news, subreddit, title) VALUES ('testing1', 'koth.gif', 'test', 'm', 'Image')
INSERT INTO posts (username, image, news, subreddit, title) VALUES ('$username', '$image', '$content', '$subreddit', '$title')
You miss a comma and a single quote before $content

ORDER BY is not working for mysql table [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have a dummy database saved in phpmyadmin.I am trying to sort the data on the basis of column user_uid.
Here is some of my database
The php code that i am using to sort the table is
<?php
include_once 'dbh.inc.php';//file contains the variables req to connect to database
$sql = "SELECT * FROM client
ORDER BY user_uid;";
$result = mysqli_query($conn,$sql);
if(($result))
{
$row = array();
($row = mysqli_fetch_array($result));
echo($row['client_name']);
}
However this doesn't seem to work.What am I doing wrong with the code?
Additional info: user_uid is a foreign key and the reference to the user_uid is from another table named users
Well in your code you have written
ORDER BY cost_per_session
Just change it to
ORDER BY user_id
you can use ASC or DESC for ascending or descending order.
Your code shows only one record. Here is a working example making use of the needed while loop to display the client_name of each fetched record:
include_once 'dbh.inc.php';
$sql = 'SELECT * FROM client
ORDER BY user_uid';
$result = mysqli_query($conn, $sql);
if ($result->num_rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo $row['client_name'] . '<br>';
}
}
I removed all the unneeded parenthesis around the vars and the semicolon at the end of the sql statement.
Good luck.
Edit 1: I corrected $connection to $conn.
Edit 2: I implemented the check on the number of rows ($result->num_rows > 0) instead of on the $result itself (which is always an object of type mysqli_result and whos check therefore always returns true - even when no records are found).

Laravel 5 Eloquent - whereIn on join table [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am trying to create an online directory, where, for example, people can search through the website and find all takeaways that have a specific type. For example:
"Indian",
"Chinese"
etc..
I have 3 tables:
Business
Tags
Business Tags
And my model is as follows:
class Business extends Model
{
protected $table = 'businesses';
protected $fillable = [
'business_name', 'postcode'
];
public function tags()
{
return $this->belongsToMany('App\Tags');
}
}
The issue is, whenever I come to do the search, and try to do a whereIn the issue is that it takes forever to load, in fact, it doesn't even load. For example:
$business = Business::whereHas('tags', function($tag) use ($request) {
if($request->get('terms'))
{
$tag->whereIn('tags.name', ['chinese']);
}
})->get();
So my question is this:
I have just over 10k rows of data stored inside the table. This table is split into three "Business", "Tags", "Business Tags". The process above is taking so long to complete, probably because I use the whereHas('tags') and whereIn therefore, how do I go about using the following syntax:
$business = Business::where( function ($business) use ($request) {
// Search for businesses with a specific tag, passed from request
});
Is this possible?
I'm just wild guessing here, but try to pull the condition outside of the function and don't specify the name of the table:
if($request->get('terms'))
{
$business = Business::whereHas('tags', function($tag) use ($request) {
$tag->whereIn('name', ['chinese']);
})->get();
}

How do I remove a row from mysql immediately after calling it?

Basically, I have a mysql database where every time I get a row, I want to delete it from the database (after reading its information).
I know I could do something like
$result = mysql_query(" SELECT <some row> FROM table ");
$row = mysql_fetch_array($result);
$id = $row["id"];
mysqli_query(" DELETE FROM table WHERE id=$id");
but now it seems I have two queries going on. Is there a command to tell mysql that I want the row deleted as soon as it gives me the information? I imagine that'd save time and resources.
In my head, it looks like
$result = mysql_query(" SELECT <some row> FROM table THEN DELETE ");
EDIT additional information: I wish to use the SELECTed information after deleting the row. To put it simply, I only want one instance of the information to exist at any give time; it would be as if I were only "moving" a physical copy of the information, so that when it is put on a device/what have you, it is no longer in the table since there is only one copy.
Sorry if my understanding of mysql is rough -- I'm pretty new to it :P
I don't know why you need it but you can use a stored procedure for that:
DELIMITER $$
CREATE PROCEDURE select_and_delete(IN aid INT)
BEGIN
SELECT * FROM table1 WHERE id = aid;
DELETE FROM table1 WHERE id = aid;
END$$
DELIMITER ;
Here is SQLFiddle demo.
mysql_* extension is deprecated, therefore use prepared statements and mysqli or PDO.
Your php code using PDO might look like
$id = 1;
try {
$db = new PDO('mysql:host=localhost;dbname=test;charset=UTF8', 'user', 'userpwd');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$query = $db->prepare("CALL select_and_delete(?)");
$query->execute(array($id));
$result = $query->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
echo "Exception: " .$e->getMessage();
$result = false;
}
$query = null;
$db = null;
//do whatever you need to do with your resultset
var_dump($result);
Following a rather simplified table structure (with the only column id) presented in SQL Fiddle example if you call it with $id=1 you'll you'll get in $result:
array(1) {
[0]=>
array(1) {
["id"]=>
int(1)
}
}
You'll need to add a timestamp field (with default as CURRENT_TIMESTAMP) to be able to tell when the row was added.
Then you can run the following MySQL query.
DELETE FROM `table` WHERE `timestamp` > DATE_SUB(NOW(), INTERVAL 0 SECOND);
You will need to run this as a cron job though. AFAIK it can't be done in MySQL alone.

Wordpress Plugin Custom Databse Query (SQL UPDATE SET WHERE)

Quick background:
CRUD plugin
WP 3.5
Creating this plugin for my personal knowledge - I'm sure one already exists.
Variables echo out ok.
The create portion of plugin needed 3 hours of research to get the query to work. Tried everything in codex, a handful of answers from Stack Overflow until something worked.
Problem:
Updating a row in a custom table.
This query will work in SQL ->
UPDATE wp_current_issue SET issue_year=9999, issue_month=29 WHERE issue_id=17;
Tried:
global $wpdb;
$wpdb->update(CURRENT_ISSUE_TABLE,
array(
'issue_year' => $issue_year,
'issue_month' => $issue_month
),
array('issue_id' => $issue_edit_id),
array('%d','%d'),
array('%d'));
As well as: (with and without backticks around column names)
global $wpdb;
$sql = $wpdb->prepare("UPDATE wp_current_issue SET issue_year=".$issue_year.", issue_month=".$issue_month." WHERE issue_id=".$issue_edit_id);
$wpdb->query($sql);
Now the funny thing is, I went through the same thing with the INSERT INTO statement. Tried everything. Only thing that would work is this:
global $wpdb;
$sql = $wpdb->prepare(
"INSERT INTO `".CURRENT_ISSUE_TABLE."` (`issue_path`,`issue_img_path`,`issue_year`,`issue_month`) VALUES (%s,%s,%d,%d)", $fileName_issue, $fileName_img, $issue_year, $issue_month);
$wpdb->query($sql);
Anyone know how I could rewrite this query for an update statement?
Assuming I understood your problem correctly if you want to rewrite that insert into an update then just use
$sql = $wpdb->prepare(
"UPDATE `".CURRENT_ISSUE_TABLE."` SET `issue_path` = %s, `issue_img_path` = %s, `issue_year` = %s, `issue_month` = %s
WHERE issue_id = %i", $fileName_issue, $fileName_img, $issue_year, $issue_month, $issue_edit_id);
The rest is the same.