I'm trying to edit many columns at one time. I have a lot of fields that I want users to be able to edit. I'm not sure exactly what I'm doing incorrectly. Any help would be greatly appreciated. It states that There was a problem with your mySQL query please contact technical support with the following information:
<?php
$dbserver = "";
$dblogin = "";
$dbpassword = "";
$dbname = "";
$con = mysqli_connect("$dbserver","$dblogin","$dbpassword","$dbname");
if (!$con)
{
die('Could not connect to the mySQL server please contact technical
support with the following information: ' . mysqli_connect_errno());
}
$organization = mysqli_real_escape_string($_POST['organization']);
$firstname = mysqli_real_escape_string($_POST['firstname']);
$lastname = mysqli_real_escape_string($_POST['lastname']);
$rank = mysqli_real_escape_string($_POST['rank']);
$branch= mysqli_real_escape_string($_POST['branch']);
$gender= mysqli_real_escape_string($_POST['gender']);
$emailaddress = mysqli_real_escape_string($_POST['emailaddress']);
$jobtitle = mysqli_real_escape_string($_POST['jobtitle']);
$company = mysqli_real_escape_string($_POST['company']);
$businessphone = mysqli_real_escape_string($_POST['businessphone']);
$homephone = mysqli_real_escape_string($_POST['homephone']);
$mobilephone = mysqli_real_escape_string($_POST['mobilephone']);
$faxnumber = mysqli_real_escape_string($_POST['faxnumber']);
$address = mysqli_real_escape_string($_POST['address']);
$city = mysqli_real_escape_string($_POST['city']);
$state = mysqli_real_escape_string($_POST['state']);
$zippostal = mysqli_real_escape_string($_POST['zippostal']);
$country = mysqli_real_escape_string($_POST['country']);
$notes = mysqli_real_escape_string($_POST['notes']);
$donorid = mysqli_real_escape_string($_POST['donorid']);
// make the query a variable so we can print out if it fails
$query = "UPDATE donors SET organization = '$organization', firstname =
'$firstname', lastname = '$lastname', rank = '$rank', branch = '$branch',
gender = '$gender', emailaddress = '$emailaddress', jobtitle = '$jobtitle',
company = '$company', businessphone = '$businessphone', homephone =
'$homephone', mobilephone = '$mobilephone', faxnumber = '$faxnumber', address =
'$address', city = '$city', state = '$state', zippostal = '$zippostal', country
= '$country', notes = '$notes', donorid = '$donorid' WHERE donorid =
'$donorid'";
$sql = mysqli_query($con,$query) or die('There was a problem with your mySQL
query please contact technical support with the following information: ' .
mysqli_error());
// troubleshooting for development only
if(mysqli_affected_rows($sql) < 1){
die('There was a problem with your mySQL query : ' . $query);}
mysqli_close($con);
header( 'Location: http://localhost/moddonor.php' ) ;
?>
Based on the conversation on #Sean answer you need to build your query dynmically, something like this should work (also it should be noted im using php5.3+ specific syntax for anon functions with array_map):
// array of field => bind type
$fields = array(
'firstname' => 's',
'lastname' => 's',
'rank' => 'i',
// other fields EXCEPT donorid
);
// template for the sql
$sqlTemplate = 'UPDATE SET %s WHERE donorid = ?';
// array to hold the fields we will actually use with the query
$params = array();
// lets check the fileds against those allowed
// and stick them in the $params array - note we exclude donorid
// because its required
foreach ($fields as $field => $type) {
if(isset($_POST[$field]) && !empty($_POST[$field])) {
$params[$field] = array(
'value' => $_POST[$field],
'type' => $type
);
}
}
// if we actually have something to update then lets prep the sql
if(!empty($params)) {
$forUpdate = array_map(function ($f) { return $field . ' = ?'; }, array_keys($params));
$sql = sprtintf($sqlTemplates, implode(',', $forUpdate));
// $sql is now the parameterized query like my example below
// compile all the parameter types into a single string like 'ssi'
$types = implode('', array_map(function($v){ return $v['type'];}, $params));
// now we need to push the $stmt and the $types onto $params
array_unshift ($params, $stmt, $types);
// params now looks like:
// Array ( 0 => Msqil_Stmt, 1 => 'ssi', 'firstname' => 'thevalue', 'lastname' => 'value', 'rank' => 1, etc..)
// now call bindparam via call_user_func_array
call_user_func_array('mysql_stmt_bind_param', $params);
// now execute the query:
mysqli_stmt_execute($stmt);
}
Youre doing muiltiple things wrong:
you are using both mysql_* and mysqli_* they are not interchangeable. Use mysqli_* because mysql_* is deprecated ans shouldnt be used anymore; All your mysql functions should be the mysqli versions.
You need quotes around your values and you also need to escape those values. Since youre using mysqli use prepared statements.
The resource connection is the second argument to the query functions, not the first.
--
// with mysqli the db name is passed as an argument wen creating the connection
$con = mysqli_connect("$dbserver","$dblogin","$dbpassword", $dbname);
if (!$con) {
die('Could not connect to the mySQL server please contact
technical support with the following information: ' . mysqli_error());
}
$sql = "UPDATE donors set organization = ?, firstname =
?, lastname = ?, rank = ?, branch = ?,
gender = ?, emailaddress = ?, jobtitle = ?, company
=?, businessphone = ?, homephone = ?,
mobilephone =?, faxnumber = ?, address = ?, city =
?, state = ?, zippostal =?, country = ?,
note = ?
WHERE donorid= ?";
$stmt = mysqli_preapre($sql);
mysqli_bind_param($stmt,
'ssisss...i',
$organization,
$firstname,
$lastname,
$rank,
$branch,
$gender,
$emailaddress,
// other feilds... the must be in the same order as named in the query
// then lastly the donorid
$donorid
);
// execute the query
mysqli_stmt_excecute($stmt);
mysqli_close($con);
header( 'Location: http://localhost/moddonor.php' ) ;
You are connecting using mysql_connect(), but using mysqli_query(). You also need to enclose your values in quotes '/"
$con = mysql_connect("$dbserver","$dblogin","$dbpassword");
...
mysql_select_db("$dbname", $con);
...
mysqli_query($con,"UPDATE donors set organization = '$organization', firstname =
'$firstname', lastname = '$lastname', rank = '$rank', branch = '$branch',
gender = '$gender', emailaddress = '$emailaddress', jobtitle = '$jobtitle', company
='$company', businessphone = '$businessphone', homephone = '$homephone',
mobilephone = '$mobilephone', faxnumber = '$faxnumber', address = '$address', city =
'$city', state = '$state', zippostal = '$zippostal', country = '$country',
note = '$note' WHERE donorid= '$donorid'");
mysqli_close($con);
Change your connection to mysqli_connect() as mysql_ functions are depreciated.
$con = mysqli_connect("$dbserver", "$dblogin", "$dbpassword", "$dbname");
if (!$con)
{
die('Could not connect to the mySQL server please contact
technical support with the following information: ' . mysqli_error());
}
mysqli_query($con,"UPDATE donors set organization = '$organization', firstname =
'$firstname', lastname = '$lastname', rank = '$rank', branch = '$branch',
gender = '$gender', emailaddress = '$emailaddress', jobtitle = '$jobtitle', company
='$company', businessphone = '$businessphone', homephone = '$homephone',
mobilephone = '$mobilephone', faxnumber = '$faxnumber', address = '$address', city =
'$city', state = '$state', zippostal = '$zippostal', country = '$country',
note = '$note' WHERE donorid= '$donorid'");
Also, it would be beneficial to learn how to do prepared statements - http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
see - http://php.net/manual/en/mysqlinfo.api.choosing.php
or http://www.php.net/manual/en/faq.databases.php#faq.databases.mysql.deprecated
EDIT
Apparently you are not setting your variables before using them in your query. note: make sure to sanitize any user inputs. see mysqli_real_escape_string()
//Put this after $con = mysqli_connect(), but before mysqli_query()
$organization = mysqli_real_escape_string($_POST['organization']);
$firstname = mysqli_real_escape_string($_POST['firstname']);
$lastname = mysqli_real_escape_string($_POST['lastname']);
....
$donorid = mysqli_real_escape_string($_POST['donorid']);
// need to add the rest of your form inputs
EDIT 2
On your updated script there are some issues - organization = $_POST['$organization'], $firstname = $_POST['$firstname'], mysql_error(), etc. Try using the following code edit.
<?php
$dbserver = "";
$dblogin = "";
$dbpassword = "";
$dbname = "";
$con = mysqli_connect("$dbserver","$dblogin","$dbpassword","$dbname");
if (!$con)
{
die('Could not connect to the mySQL server please contact technical support with
the following information: ' . mysqli_connect_errno());
}
$organization = mysqli_real_escape_string($_POST['organization']);
$firstname = mysqli_real_escape_string($_POST['firstname']);
$lastname = mysqli_real_escape_string($_POST['lastname']);
$rank = mysqli_real_escape_string($_POST['rank']);
$branch= mysqli_real_escape_string($_POST['branch']);
$gender= mysqli_real_escape_string($_POST['gender']);
$emailaddress = mysqli_real_escape_string($_POST['emailaddress']);
$donorid = mysqli_real_escape_string($_POST['donorid']);
// make the query a variable so we can print out if it fails
$query = "UPDATE donors SET organization = '$organization', firstname = '$firstname', lastname = '$lastname', rank = '$rank', branch = '$branch', gender = '$gender', emailaddress = '$emailaddress' WHERE donorid = '$donorid'";
$sql = mysqli_query($con,$query) or die('There was a problem with your mySQL query please contact technical support with the following information: ' . mysqli_error());
// troubleshooting for development only
if(mysqli_affected_rows($sql) < 1){
die('There was a problem with your mySQL query : ' . $query);}
mysqli_close($con);
header( 'Location: http://localhost/moddonor.php' ) ;
You didnt mention whats the error but,
I think you must wrap the values using single quote ('), for example
set organization = $organization
becomes
set organization = '$organization'
Related
I am a beginner when we talk about PHP. SO I have no idea where I made a mistake using PHP.
<?php
require "conn.php";
$name = "yolo";
$surname = "yolo";
$nameOfFee= "asd";
$date = '2012-08-06';
$mysql_query = "(INSERT INTO Relation (Person_ID, Fee_ID, Date_of_fee)
SELECT Person.ID,Fee.ID,'$date'
FROM Person,Fee
WHERE Person.Name = '$name' AND Person.Surname = '$surname' AND Fee.Name_of_fee = '$nameOfFee');";
if($conn->query($mysql_query) === TRUE){
echo "Insert completed";
}
else{
echo "Insert not completed";
}
$conn->close();
?>
It always puts that Insert is not complete...
The Problems
There are a few syntax errors in this piece of code you have provided:
// here it starts, what is this "(" for before insert?
// Take note that your query is vulnerable to SQL attacks
$mysql_query = "(INSERT INTO Relation (Person_ID, Fee_ID, Date_of_fee)
SELECT Person.ID,Fee.ID,'$date'
FROM Person,Fee
WHERE Person.Name = '$name' AND Person.Surname = '$surname' AND Fee.Name_of_fee = '$nameOfFee');";
How to fix it
To fix these things I recommend you use the MySQLi OOP, like you are using now, but add prepared statements. I will walk through the new code with you so you can understand the process.
require "conn.php";
$name = "yolo";
$surname = "yolo";
$nameOfFee= "asd";
$date = '2012-08-06';
$sql = "INSERT INTO Relation (Person_ID, Fee_ID, Date_of_fee) VALUES (?, ?, ?)"; // rewrite your query with a preset number of values to prevent SQL Attacks
if($stmt = $conn->prepare( $sql ))
{ // before we run check to make sure the query worked
$stmt->bind_param('sss', $name, $nameOfFee, $date); // bind your variables so to know what goes where
$stmt->execute(); // execute the query
$stmt->close(); // close connection for safety
// message as an array for the user as feedback.
$message = array(
'is_error' => 'success',
'message' => 'Record was entered into database.'
);
}
else
{
$message = array(
'is_error' => 'danger',
'message' => 'Query Error, please revise the information.'
);
}
I am trying to enter data from html into MSSQL database using php. I am unable to insert record in 2 different tables and unable to insert multiple records to a table, I have the code below
<?php
$name = $_POST["name"];
$email = $_POST["email"];
$company = $_POST["company"];
$contact = (int)$_POST["contact"];
$worktitle = $_POST["worktitle"];
$industry = $_POST["industry"];
$V101 = $_POST["part2q1"];
$V102 = $_POST["part2q2"];
$V103 = $_POST["part2q3"];
$V104 = $_POST["part2q4"];
$V105 = $_POST["part2q5"];
$V106 = $_POST["part2q6"];
$V107 = $_POST["part3q1"];
$V108 = $_POST["part3q2"];
$V109 = $_POST["part3q3"];
$V110 = $_POST["part3q4"];
$V111 = $_POST["part3q5"];
$V112 = $_POST["part3q6"];
$V113 = $_POST["part4q1"];
$V114 = $_POST["part4q2"];
$V115 = $_POST["part4q3"];
$V116 = $_POST["part4q4"];
$V117 = $_POST["part4q5"];
$V118 = $_POST["part4q6"];
$V119 = $_POST["part5q1"];
$V120 = $_POST["part5q2"];
$V121 = $_POST["part5q3"];
$V122 = $_POST["part5q4"];
$V123 = $_POST["part5q5"];
$V124 = $_POST["part5q6"];
$V125 = $_POST["part6q1"];
$V126 = $_POST["part6q2"];
$V127 = $_POST["part6q3"];
$V128 = $_POST["part6q4"];
$V129 = $_POST["part6q5"];
$V130 = $_POST["part6q6"];
$V131 = $_POST["part7q1"];
$V132 = $_POST["part7q2"];
$V133 = $_POST["part7q3"];
$V134 = $_POST["part7q4"];
$V135 = $_POST["part7q5"];
$V136 = $_POST["part7q6"];
$V137 = $_POST["part7q7"];
$V138 = $_POST["part7q8"];
$V139 = $_POST["part8q1"];
$V140 = $_POST["part8q2"];
$V141 = $_POST["part8q3"];
$V142 = $_POST["part8q4"];
$V143 = $_POST["part8q5"];
$V144 = $_POST["part8q6"];
$currenttime = date("Ymd h:m:sa");
$server = "***";
$connOptions = array("Database"=>"**", "UID"=>"**", "PWD"=>"**!");
$conn = sqlsrv_connect($server, $connOptions);
if($conn){
$query="INSERT INTO dbo.profile (
name,
email,
company,
telephone,
worktitle,
industry,
createdate
)
VALUES (?, ?, ?, ?, ?, ?,getdate())";
$params = array(
$name,
$email,
$company,
$contact,
$worktitle,
$industry,
$currenttime
);
if(sqlsrv_query($conn, $query, $params)){
echo "<h4>Thank you</h4><p>You have completed the survey and your answers have been received.</p>";
} else {
echo "<p>We're sorry but there has been and error receiving your answers.</p>";
}
} else {
echo "<p>We're sorry but there has been and error receiving your answers. </p>";
}
Im trying to insert records to another table like this continuing from the previous line:
if($conn){
$query1="INSERT INTO dbo.SurveyResponse (
profileid,
Value,
CreatedOn
)
VALUES ('2', ?, ?, ?, ?, ?,getdate())";
$params=array($V101,$currenttime);
$query1="INSERT INTO dbo.SurveyResponse (
profileid,
Value,
CreatedOn
)
VALUES ('2', ?, ?, ?, ?, ?,getdate())";
$params=array($V102,$currenttime);
$query1="INSERT INTO dbo.SurveyResponse (
profileid,
Value,
CreatedOn
)
VALUES ('2', ?, ?, ?, ?, ?,getdate())";
$params=array($V103,$currenttime);
. . . . .
if(sqlsrv_query($conn, $query1, $params))
{
echo "<h4>Thank you</h4><p>You have completed the survey and your answers have been received.</p>";
} else {
echo "<p>We're sorry but there has been and error receiving your answers.</p>";
}
} else {
echo "<p>We're sorry but there has been and error receiving your answers. </p>";
}
?>
I have been trying this, insert works for first table but not the second table, can anyone help please
The following worked for me to enter multiple records to second table. Thanks to Miken32
if($conn){
$query1="INSERT INTO dbo.SurveyResponse (
profileid,
Qid,
Value,
CreatedOn
)
VALUES (?, ?, ?,getdate())";
$params1=array(2,101,$V101,$currenttime);
if(sqlsrv_query($conn, $query1, $params1))
{
echo "";
}
else { echo"<p>We're sorry but there has been and error receiving your answers.</p>" ; }
}
if($conn){
$query2="INSERT INTO dbo.SurveyResponse (
profileid,
Qid,
Value,
CreatedOn
)
VALUES (?, ?, ?,getdate())";
$params2=array(2,102,$V102,$currenttime);
if(sqlsrv_query($conn, $query2, $params2))
{
echo "";
}
else { echo"<p>We're sorry but there has been and error receiving your answers.</p>" ; }
}
Hi I am having an issue with code not working on a server but working within my local environment using Xampp. The Issues I am having are:
First Prepared Statement Only Gets Implemented
usersId is not returned (couldn't get last_insert_id() to work)
I was using PHP on xampp but thought this was due to the server being PHP5 and there being version issues but I updated my Xampp to PHP5 and this problem still occurs.
mysqli_autocommit($conn,FALSE);
$insertUser = "INSERT INTO users(username, password) VALUES (?,?)";
$userStatement = $conn->prepare($insertUser);
$userStatement->bind_param("ss", $u, $p);
$u = $username;
$p = $encryptedPassword;
$userStatement->execute();
$userStatement->close();
$id = "";
$query = "SELECT userid from users WHERE username = '$username'";
$resultID = mysqli_query($conn, $query) or die($query."<br/> <br/>".mysql_error());
if($resultID == false){
echo "ERROR1";
}
else {
foreach($resultID as $row){
$userid = $row['userid'];
}
}
$buildbirthday = "{$day}/{$month}/{$year}";
$insertDetails = "INSERT INTO userdetails(userid, firstname, lastname, birthdate, email) VALUES (?, ?, ?, ?, ?)";
$detailsStatement = $conn->prepare($insertDetails);
$detailsStatement->bind_param("issss", $i, $f, $n, $b, $e);
$i = $userid;
$f = $firstname;
$n = $secondname;
$b = $buildbirthday;
$e = $email;
$detailsStatement->execute();
$detailsStatement->close();
My PHP form I just changed to use PDO. The only thing I can tell is the execute is not working. Am I supposed to pass something with it?
$db = new PDO('mysql:host=localhost;dbname=x;charset=utf8', 'x', 'x');
if ( !$db )
{
die('Could not connect: ' . mysql_error());
}
$ipaddress = $_SERVER['REMOTE_ADDR'];
$mail = $_POST['mail'];
$stmt = $db->prepare("SELECT * FROM ucm_signup WHERE email =? ");
$stmt->bindValue(1, $mail, PDO::PARAM_STR);
$stmt->execute();
if($stmt->rowCount()== 0) {
//if there are no duplicates...insert
$sql = $db->prepare("INSERT INTO ucm_signup (company, address1, address2, city, province, zip, fname, lname, email, phone, session, iama, buyfrom, group1, ipaddress)
VALUES (:company, :address1, :address2, :city, :province, :zip, :fname, :lname, :mail, :phone, :session, :iama, :buyfrom, :group1, :ipaddress)");
$sql->bindParam(":company", $_POST['company'],PDO::PARAM_STR);
$sql->bindParam(":address1", $_POST['address1'],PDO::PARAM_STR);
$sql->bindParam(":city", $_POST['city'],PDO::PARAM_STR);
$sql->bindParam(":province", $_POST['province'],PDO::PARAM_STR);
$sql->bindParam(":zip", $_POST['zip'],PDO::PARAM_STR);
$sql->bindParam(":fname", $_POST['fname'],PDO::PARAM_STR);
$sql->bindParam(":lname", $_POST['lname'],PDO::PARAM_STR);
$sql->bindParam(":email", $_POST['email'],PDO::PARAM_STR);
$sql->bindParam(":phone", $_POST['phone'],PDO::PARAM_STR);
$sql->bindParam(":session", $_POST['session'],PDO::PARAM_STR);
$sql->bindParam(":imea", $_POST['imea'],PDO::PARAM_STR);
$sql->bindParam(":buyfrom", $_POST['buyfrom'],PDO::PARAM_STR);
$sql->bindParam(":imea", $_POST['imea'],PDO::PARAM_STR);
$sql->bindParam(":group1", $_POST['group1'],PDO::PARAM_STR);
$sql->bindParam(":ipaddress", $_POST['ipaddress'],PDO::PARAM_STR);
$sql->execute();
}
My database table has no records. Thank you
You are missing some placeholder in your bind parameters, check them carefully
$sql->bindParam(":address1", $_POST['address1'],PDO::PARAM_STR);
$sql->bindParam(":address2", $_POST['city'],PDO::PARAM_STR);
//address2 was missed, probably error is column doesn't match values
$sql->bindParam(":email", $_POST['email'],PDO::PARAM_STR); //supposed to be mail
$sql->bindParam(":imea", $_POST['imea'],PDO::PARAM_STR); //supposed to be iama
You might want to check for pdo errors, here an example taken from manual
$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
With this attribute correctly added pdo will notify you if any error occur
PHP users are so PHP users.
First they're laboring on a WALL of code, consists of constantly repeating nearly hundred variables.
Then they get totally lost.
While everything can be done with short and concise code, writing each field name only ONCE
$allowed = array('company', 'address1', 'address2', 'city', 'province',
'zip', 'fname', 'lname', 'email', 'phone', 'session',
'iama', 'buyfrom', 'group1', 'ipaddress');
$_POST['ipaddress'] = $_SERVER['REMOTE_ADDR'];
$sql = "INSERT INTO ucm_signup SET ".pdoSet($allowed, $values);
$stm = $dbh->prepare($sql);
$stm->execute($values);
where pdoSet() helper function can be stored elsewhere and reused for the every insert or update query
function pdoSet($fields, &$values, $source = array()) {
$set = '';
$values = array();
if (!$source) $source = &$_POST;
foreach ($fields as $field) {
if (isset($source[$field])) {
$set.="`".str_replace("`","``",$field)."`". "=:$field, ";
$values[$field] = $source[$field];
}
}
return substr($set, 0, -2);
}
I've a few examples but nothing that I can grasp. I have the below code, the echos work but the insert does not. I believe I'm suppose to explode these? Not sure but maybe someone can give me a hint with my own example.
$con=mysqli_connect(localhost,"username","password","db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$deletetable = $con->prepare('TRUNCATE TABLE twitch_streams');
$deletetable->execute();
$deletetable->close();
$result = $con->prepare("SELECT field_value
FROM xf_user_field_value
WHERE field_id = 'twitch'
AND field_value != ''");
$result->bind_result($twitchfield);
while($result->fetch())
{
printf("%s\n", $twitchfield);
$username[] = $twitchfield;
$data = json_decode(file_get_contents('http://api.justin.tv/api/stream/l ist.json?channel=' . $username[0]));
$viewer[] = $data[0]->channel_count;
$insert = $con->prepare("INSERT INTO twitch_streams (twitchuser, viewercount)
VALUES (?, ?)");
$insert = bind_param('si', $twitchuser, $viewercount);
$twitchuser = $username[0];
$viewercount = $viewer[0];
$insert->execute();
echo $twitchuser;
echo $viewercount;
$insert->close();
}
$result->close();$deletetable = $con->prepare('TRUNCATE TABLE twitch_streams');
$deletetable->execute();
$deletetable->close();
$result = $con->prepare("SELECT field_value
FROM xf_user_field_value
WHERE field_id = twitch
AND field_value != ''");
$result->bind_result($twitchfield);
while($result->fetch())
{
printf("%s\n", $twitchfield);
$username[] = $twitchfield;
$data = json_decode(file_get_contents('http://api.justin.tv/api/stream/l ist.json? channel=' . $username[0]));
$viewer[] = $data[0]->channel_count;
$insert = $con->prepare("INSERT INTO twitch_streams (twitchuser, viewercount)
VALUES (?, ?)");
$insert = bind_param('si', $twitchuser, $viewercount);
$twitchuser = $username[0];
$viewercount = $viewer[0];
$insert->execute();
echo $twitchuser;
echo $viewercount;
$insert->close();
}
$result->close();
mysqli_close($con);
You're missing quotes around your string values:
"INSERT INTO twitch_streams (twitchuser, viewercount)
VALUES ($username[0], $viewer[0])"
should be
"INSERT INTO twitch_streams (twitchuser, viewercount)
VALUES ('$username[0]', '$viewer[0]')"
You would spot this error easily if you add error handling to your code. Look into using mysqli_error().
$result = mysqli_query($con,"INSERT INTO twitch_streams (twitchuser, viewercount)
VALUES ('$username[0]', '$viewer[0]')");
if (!result) {
// This should be done better than this
echo mysqli_error();
exit;
}
Since I can't tell from your code what the source of $data[0]->channel_count is I will also mention that you should at least escape your insert variables with mysqli_real_escape_string(). Even better, use prepared statements.