-2

I’m trying to insert values into one table from another table as well as the variable which stores the username. The code below is currently what I have but it’s returning errors. (Currently don’t have access to my code to give the errors) There is a connection to the database above this.

<?php
session_start();
$users = $_SESSION['username'];
$sql = “INSERT INTO squads(username,
age, name, rating, value)  VALUES
$users AND SELECT FROM players
age, name, rating, value”;
mysqli_query($connection, $sql)
  • _"Is there anyway I can do this?"_ - probably, but so far, this question is lacking any sort of useful details. Please go read [ask], and then edit it accordingly. – CBroe May 12 '22 at 08:30
  • @ADyson that helps with getting the data from one table to another but not adding in the variables from my webpage. – Callum Flear May 12 '22 at 08:55
  • It can do both. Look carefully at the example in the accepted answer. Notice that hard-coded `1`? That doesn't come from the selected table. You can put any value you want into the SELECT as well as just column names, including inserting parameters which come from your PHP variables. – ADyson May 12 '22 at 08:57
  • @ADyson I tried doing that and it returned this error "Fatal error: Uncaught mysqli_sql_exception: Unknown column 'CALLUM' in 'field list'" CALLUM is the variable stored in $users – Callum Flear May 12 '22 at 10:21
  • What _exactly_ did you write as the query, then? Remember that literal values need to be enclosed in single quotes in a SQL statement (unless they are numbers). You should be parameterising your query though anyway, so that kind of thing ought not to be an issue. Any reason you're not following established security (and reliability) best practice in that respect? https://phpdelusions.net/mysqli shows simple examples of writing safe SQL using mysqli's prepared statements and parameters functionality. – ADyson May 12 '22 at 10:53
  • @ADyson $sql = “INSERT INTO squads(username, age, name, rating, value) SELECT ‘$users’, age, name, rating, value FROM players; – Callum Flear May 12 '22 at 10:56
  • Did you use those actual quote marks (`\` ` and `’`) or is that just artefact of typing it into here? Always paste your real code, don't transcribe it. You need to use single quotes (`'`) rather than anything else. BUT as I said above, you should be using prepared statements and parameters in all cases anyway, which will make this specific problem completely redundant. Again...why aren't you already doing that? – ADyson May 12 '22 at 11:15

0 Answers0